Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Set Django X-CSRFToken Using Axios in Django
I am using Django + ReactJS for my latest web apps. I have csrf enabled for my django backend. In this case, I need to set headers["X-CSRFToken"] = csrfToken for my POST requests. The current way I am using is Using {% csrf_token %} tag in django template which will generate a hidden input with value=csrfToken and before every axios calls add: let csrf = document.querySelector("[name=csrfmiddlewaretoken]").value; axios.interceptors.request.use(function (config) { config.headers["X-CSRFToken"] = csrf; return config; }, function (error) { return Promise.reject(error); }); However, I want to set the csrf header to global axios settings, so I can avoid setting it every time I want to call. Can I know how can I do it? If I set it in the base index.js of react, it will return me Uncaught TypeError: Cannot read property 'value' of null Because the csrf input element is not rendered yet. I also tried to put it into the React Component's componentDidMount method, still, the same error. -
Pycharm does not warn about unresolved references
I'm using Pycharm Community to develop a project using the Django Framework. I have recently created a new project and it's working perfectly. The only problem is that Pycharm doesn't complain about unresolved references on python code. In my other django projects, when i call a funtion that has not been imported like "get_user_model()" django underlines the function call with a red line and it asks if i want to import that function. But in this project, it doesn't even complain about that. I only see the error once i hit run. There is no real-time checking, no graphical debbuger. Some configuration is missing. Could you give me some tips? -
How to get push-notification in django when database has been updated with a new entry?
I want to generate a push-notification whenever the database entry is updated if the current ID is 2 and a new tuple is added the id would be 3. so how can i be notified if that new id has been added to the database? The data entry is done on the back-end by some python script no data has been added to the MySQL database by the user. So every time a new tuple is added to the database I want my application to give me notification. I am posting everything that might be relevant for your ease. please hep me with the code. models.py creates table Offenses in the database models.py class Offenses(models.Model): oid = models.IntegerField(primary_key=True) description = models.CharField(null=False, max_length=200) objects = UserManager() class Meta: db_table = "offenses" from views.py i am adding entries to the database that has been retrieved from an API and stored in the database.here is the snippet of my views.py response_body = json.loads(response.read().decode('utf-8')) for j in response_body: obj, created = Offenses.objects.get_or_create(oid=j['id'], defaults={'description': j['description'], 'assigned_to': j['assigned_to']}) return render(request, 'table.html') -
How to access class attribute from within Meta class
I'm adding field-level permissions to my model. I want to keep them separate from the other object-level permissions so my code can check to see if a permission has been defined for any given field, but then I still want to combine them so the field-level permissions get created in the auth_permission table. I first tried creating field_permissions inside the Meta class, but got the "class Meta got invalid attribute(s)" error. I then moved field_permissions out of the Meta class, as a model class attribute, and tried to append it to "permissions" (defined in the Meta class), but I get an "unresolved reference" on field_permissions inside the Meta class. I also tried self.field_permissions, but that doesn't work either. Here's my model: class Client(AddressPhoneModelMixin, DateFieldsModelMixin, models.Model): name = models.CharField( verbose_name=_('Client'), max_length=100, ) status = models.CharField( verbose_name=_('Status'), max_length=25, ) field_permissions = ( ('view_client_id', 'Can view client ID'), ('view_client_name', 'Can view client name'), ('view_client_address', 'Can view client address'), ('view_client_country', 'Can view client country'), ('view_client_status', 'Can view client status'), ('view_client_phone_number', 'Can view client phone number'), ('view_client_mobile_number', 'Can view client mobile number'), ('view_client_fax_number', 'Can view client fax number'), ('view_client_created', 'Can view client created'), ('view_client_updated', 'Can view client updated'), ('view_client_deleted', 'Can view client deleted'), ('change_client_id', 'Can … -
How to customize the schema in APIView
I have two class, CustomAPIView and ContestMessageAPI, where the ContestMessageAPI inherits from CustomAPIView. The specific structure is as follows (the irrelevant method is omitted): class CustomAPIView(APIView): """ Custom APIView """ authentication_classes = (JSONWebTokenAuthentication,) class ContestMessageAPI(CustomAPIView): """ Pass in the contest_id to get the corresponding match information """ Now I am modifying a parameter in the ContestMessageAPI class so that I can implement a function. class ContestMessageAPI(CustomAPIView): """ Pass in the contest_id to get the corresponding match information """ parameter = {'contest_id': 'Field description'} schema = AutoSchema(manual_fields=[ coreapi.Field(name=k, required=True, location="form", schema=coreschema.String(description=v)) for k, v in parameter.items() ]) Since the fragments assigned to the schema code are fixed, I want to port this code to its parent class CustomAPIView, and CustomAPIView becomes class CustomAPIView(APIView): """ 自定义的APIView """ authentication_classes = (JSONWebTokenAuthentication,) parameter = {'contest_id':'字段描述'} schema = AutoSchema(manual_fields=[ coreapi.Field(name=k, required=True, location="form", schema=coreschema.String(description=v)) for k, v in parameter.items() ]) Then I want to configure the parameter variable in the ContestMessageAPI to implement the schema that modifies its parent class, but the discovery fails. After querying the data, the reason may be: the rule for loading the member variable is to load the member variable of the parent class first, and then load the member variable … -
How to use multiple functions on Jupyter Notebook as an api and call this api from Django?
I am making a movies prediction model in Jupyter Notebook and want to use this model in Django where I am making web application. But I don't know how to do it -
How to make the user pay for something online
I am making a bookstore website and I want the user to be able to pay for the books online with credit card or visa etc .. how to do this in django is there a library for this ?? -
Search everythings using django filter
I am trying to search everything related to Warnings table. I use django filter to search but no returned result. I also refer some code using django filter and follow them but nothing. How do I solve? Here are some code. filters.py import django_filters from .models import Warnings class WarningFilter(django_filters.FilterSet): title = django_filters.CharFilter(lookup_expr='icontains') detail = django_filters.CharFilter(lookup_expr='icontains') type = django_filters.CharFilter(lookup_expr='icontains') website = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Warnings fields = ['title', 'detail', 'type', 'website'] views.py def search(request): if request.method == 'GET': query = request.GET.get('q') result = WarningFilter(query, queryset=Warnings.objects.all()) context = {'filters': result.qs} return render(request, 'pages/history_warning.html', context) models.py from django.db import models from django.contrib.auth.models import User import uuid class Website(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=200) uri = models.CharField(max_length=200) def __str__(self): return self.name class Warnings(models.Model): TYPE_WARNINGS = ( ('security', "Cảnh báo bảo mật"), ('service', "Cảnh báo dịch vụ") ) title = models.CharField(blank=True, null=True, max_length=255) detail = models.TextField(blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True, blank=True, null=True) type = models.CharField(choices=TYPE_WARNINGS, blank=True, null=True, max_length=255) website = models.ForeignKey(Website, on_delete=models.CASCADE) def __str__(self): return self.title -
How do I convert my Django app to use form validation correctly using Django forms?
I have an existing application that works as it exists. As of right now, I obtain data from a POST request, retrieve it one by one, and then perform some logic. Here is some of my existing code: last_name = request.POST.get('last_name') first_name = request.POST.get('first_name') mi = request.POST.get('mi') street_line1 = request.POST.get('street_line1') #sanitize if last_name == None: return HttpResponse("Invalid last name.", status=422) if first_name == None: return HttpResponse("Invalid first name.", status=422) if street_line1 == None: return HttpResponse("Invalid address line 1.", status=422) street_line2 = request.POST.get('street_line2') street_line3 = request.POST.get('street_line3') city = request.POST.get('city') # sanitize if city == None: return HttpResponse("Invalid city.", status=422) etc. For each field in my model, I pull it manually, then do some sanitization (which, for most of my fields, is simply making them required.) Once I pull all of my data, I grab some things from my JWT, and the primary key from my POST request, then I do some logic to determine if the primary key (surrogate_id) already exists. If it does, I update the data. If it does not, I create a new instance in the db. This happens like so: # Grab the pidm from the JWT user_pidm = Identity.objects.get(username=payload['username']).pidm # grab the surrogate_id sur_id = Contact.objects.filter(surrogate_id=surrogate_id) … -
Get lenght of searched output
I have a ListView in Django to return all users that match a keyword(username, first_name, last_name) from search bar on my page. Code looks like this class SearchView(ListView): model = User template_name = 'blog/list_of_users.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user_name = self.request.GET.get('search', '') if len(user_name) < 1: context['all_search_results'] = False return context context['all_search_results'] = User.objects.filter(username__icontains=user_name ) or User.objects.filter(last_name__icontains=user_name ) or User.objects.filter(first_name__icontains=user_name ) return context And I'm showing in in template this way : {% if not all_search_results %} <div class="alert alert-danger"> No User </div> {% else %} {% for result in all_search_results %} {{ result.username }} etc..... And I would like to show length of matched result on my template. How should I change my code for that? -
How to authenticate a user in a unit test for the Django admin page?
I'm trying to adapt the answer from Testing custom admin actions in django, but I'm running into some unexpected behavior. I've created a simplified Django app, myapp, which has a Worker and Invoice model: class Worker(models.Model): name = models.CharField(max_length=255) class Invoice(models.Model): UNPAID = 0 PAID = 1 worker = models.ForeignKey( 'Worker', on_delete=models.CASCADE) amount = models.DecimalField( max_digits=10, decimal_places=2) amount_paid = models.DecimalField( max_digits=10, decimal_places=2, default=Decimal('0.00')) status = models.IntegerField( choices=[(UNPAID, 'Unpaid'), (PAID, 'Paid')], default=0) I've create a custom admin action called mark_as_paid which changes the status of the selected invoices to Invoice.PAID in admin.py: from django.contrib import admin from django.db.models import F from .models import Invoice @admin.register(Invoice) class InvoiceAdmin(admin.ModelAdmin): list_display = ('worker', 'status', 'amount', 'amount_paid') actions = ['mark_as_paid'] def mark_as_paid(self, request, queryset): queryset.update(amount_paid=F('amount')) I'm trying to test this like so: from decimal import Decimal from django.contrib import admin from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse from myapp.models import Invoice, Worker class InvoiceAdminTests(TestCase): def setUp(self): self.user = User.objects.create_user( username='foobar', email='foo@bar.com', password='barbaz', is_superuser=True) self.client.force_login(user=self.user) def test_mark_as_paid(self): worker = Worker.objects.create(name="John Doe") invoice = Invoice.objects.create( worker=worker, amount=Decimal('100.00')) response = self.client.post( reverse('admin:myapp_invoice_changelist'), data={ 'action': 'mark_as_paid', admin.ACTION_CHECKBOX_NAME: [invoice.id]}) import ipdb; ipdb.set_trace() invoice.refresh_from_db() self.assertEqual(invoice.amount_paid, Decimal('100.00')) I've set a debugger trace in the test, but ultimately … -
Update model field based on edit form input django
I'm using tesseract to read in numbers in an image. I have a model with a boolean field that is dependent on the largest number found in the image. It's True if the largest number found is less than 90 and False otherwise. When the user submits the form, the boolean value is correctly updated (image_view). The problem is I created an edit form, and I'm trying to update the boolean value based on the new user input. I tried to define a function good_candidacy in the editPartView() that will update the boolean value if the user updates the dimension, but it currently does not work. views.py def image_view(request): if request.method == 'POST': form = partForm(request.POST, request.FILES) if form.is_valid(): image_file = request.FILES.get('image') text_content = pytesseract.image_to_string(Image.open(image_file)) Serial_number = request.POST.get('Serial_number') text_list = text_content.split() new_list = [] # ----- code for cleaning string and putting it into new_list... is_good_candidate = False if max(new_list) < 90: is_good_candidate = True x = Component(Serial_number = Serial_number, text=text_content, image=image_file, dimension1=max(new_list), Good_Candidate = is_good_candidate) x.save() return redirect('editPart', Serial_number) else: form = partForm() return render(request, 'home.html', {'form': form,}) class editPartView(UpdateView): model = Component form_class = editForm template_name = "edit_form.html" def good_candidacy(self, form): to_edit = get_object_or_404(Component,pk=self.kwargs['serial_number']) dimension1 = to_edit.dimension1 if … -
Why do I need to use asynchronous tools for sending Django email
While using Django, I had noticed when I send an email there is a delay and to overcome this I had to use Celery tool. So I wanted to know what is actually happening under the hood. Why does Django/Python need an async tool to accomplish this task. I have learned about MultiThreading, MultiProcessing in Python but if somebody could give me a brief idea about what exactly is happening when Django is trying to send an email without using Celery. -
How get a login token from Django after doing Google sign in on Android?
What I have: Django with Rest Framework (drfx), Allauth + socialaccount + Google provider setup on my local server. When I go to /accounts/google/login I can log in fine in my browser and I am returned to /accounts/google/login/callback like normal and I can use my account perfectly fine. On Android: My Google login is working fine. The app logs in with Google, creates an ID Token which I now have to send to my server. I have no idea how to connect to my server at all. What kind of request should I be making so I can get an authentication key? I know I'm supposed to be making a POST request with the ID Token but I have no idea how to send it. This is what Google suggests I do, I don't know what URL to send and what parameters/headers/etc. to POST. https://developers.google.com/identity/sign-in/android/backend-auth HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("https://yourbackend.example.com/tokensignin"); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("idToken", idToken)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); final String responseBody = EntityUtils.toString(response.getEntity()); Log.i(TAG, "Signed in as: " + responseBody); } catch (ClientProtocolException e) { Log.e(TAG, "Error sending ID token to backend.", e); … -
Postgresql get updated by sql script, get notification in backend
I'm using django-rest-framework as backend and postgresql as the database. The database might be changed by raw SQL script and I want to get notified in the backend when those changes happen so that I can notify different users about the change. I've checked about posts like https://gist.github.com/pkese/2790749 for receiving notification in python and some SQL scripts for CREATE TRIGGER rec_notify_trig AFTER INSERT OR UPDATE OR DELETE ON rec FOR EACH ROW EXECUTE PROCEDURE rec_notify_func() My question is that I don't know how to hook them together in the django-rest-framework, like where should I put the SQL script, where to put the python settup so that I can connect them together. Any advice will be appreciated. -
How to remove the selection option from the admin panel
If an option has been selected once, how to remove the selection option from the admin panel admin.py class MyModelForm(forms.ModelForm): LOC = [('op1', 'op1'), ('op2', 'op2'),...] LI = [i.location for i in list(DataModel.objects.all())] X = [] for i, j in LOC: if i not in LI: X.append((i, j)) print(X) print(LI) location = forms.ChoiceField(choices=X) class DataModelAdmin(admin.ModelAdmin): form = MyModelForm list_display = ('location',) search_fields = ['location'] def get_ordering(self, request): return ['location'] admin.site.register(DataModel, DataModelAdmin) model.py class DataModel(models.Model): location = models.CharField(max_length=50, unique=True) def __str__(self): return self.location I try to do but it remove the option on restart the server -
Heroku Config Vars and Django
I want to make specific settings for each environment (local vs staging). I set up Config Vars in my heroku staging app and set DEBUG setting to false to try it out, but it didn't work. Am I missing something or making it wrong? My seetings.py file Config Vars in the staging app Result when I tried somthing wrong -
Using django-filter with class DetailView
I want to make a dynamic filtering form with Django and django-filter like stackoverflow filter and i want to use this filter on a template that render by DetailView , now the problem is i searched alot and i didn't found example of how to make this happen in my template i list all 'courses' that related to 'materials' class and i want to make a form on the same template so i can filter this list my template {% for course in material_detail.courses_set.all %} <div class="course"> <h5>{{ course.course_name }}</h5> <p>{{ course.course_description }} </p> </div> <hr/> {% endfor %} I have two models 'Materials' and 'Courses' my models.py class Materials(models.Model): materials_name = models.CharField(max_length=200) materials_description = models.CharField(max_length=200, null=True) slug_material = models.SlugField(blank=True, unique=True) class Courses(models.Model): course_name = models.CharField(max_length=200) course_description = models.CharField(max_length=300, null=True) material = models.ForeignKey(Materials, on_delete = models.CASCADE) and i have one Class DetailView my views.py class MaterialsDetailView(DetailView): model = Materials template_name = 'tuts/material.html' context_object_name = 'material_detail' I have made a filters.py file and make this code on it , but i don't know how to link this with my Class DetailView import django_filters from .models import Materials class CourseFilter(django_filters.FilterSet): class Meta: model = Materials fields = ['courses__course_name', 'courses__course_description'] Note: there are … -
How can I automatically test or check that the attributes used in __str__ exist in the class of my Django model?
In a Django 2.2 project, I renamed an attribute in a django.db.models.Model class. This attribute was used in __str__ but I forgot to rename it in the __str__ method of this class. I discovered this bug quite late, when testing something about this class in a Django shell. Is there a code testing app/framework/suite that could look for this kind of bug automatically? If not, how would a test checking that all attibutes used in __str__ actually exist in the class look like? -
Django sql query with None in field of WHERE clause not working
I am having issues when writing sql query for django. If the query is Books.objects.filter(id=1, name='ABC'), the sql query using django.db.connection would be: cur = connection.cursor() cur.execute('SELECT title FROM book WHERE id = %s AND name = %s',[id, name]) This works if there is a value in the name field but returns [] if name is None. So what should the equivalent be for Books.objects.filter(id=1, name=None)? What would be the query to accommodate both None and other values. cur = connection.cursor() for id, name in [(),(),()]: cur.execute('SELECT title FROM book WHERE id = %s AND name = %s',[id, name]) Expected result is the rows from the table but actual result is []. -
migrating problems when porting django project to python 3 and django 2
I've been porting a Django project to python 3 and Django 2. I have had to add on_delete to all my models with foreign keys as required in Django 2. Now I have tried to make migrations for those changes have been getting TypeError: __init__() missing 1 required positional argument: 'on_delete' the file it references is the 0002 migration file not the models file which has been updated. I am not sure how to go about fixing this. I have tried faking the migrations and I still get the same error. I am not sure why it thinks the database doesn't exist, I have checked and everything is intact and working in postgres. Any ideas? -
Django Forms - How to make a form inputs type equal to "date"
I am using a django form to create two inputs for date. When created in html the input types are set to type="text". How can I make theses be created with type="date". forms.py class searchForm(forms.Form): datestart = forms.DateField(label="Date Start") dateend = forms.DateField(label='Date end') views.py def search(request): if request.method == 'POST': form = searchForm(request.POST) if form.is_valid(): print(form) else: form = searchForm() return render(request, 'next_launch/search.html',{'form': form}) search.html <form action="search" method="post"> {% csrf_token %}} {{ form }} <input type="submit" value="Submit"> </form> -
Is there a way to integrate a Django application with a pre-existing Squarespace site?
I have a client who has a pre-made Squarespace site who has asked me to build polling and article pages as well as a user database. I did this using django, but am unsure if I can integrate the third party application with their site. I contacted squarespace, they told me they themselves do not provide support on third party applications. They pointed me towards forums to gather more information. Any information would help. -
URL rewriting with Django
The Problem I want to solve is the following: E.g. we have https://example.com/?id=e46Hd3cDe. But I want to make it look nicer so I want users to be able to go to this link: https://example.com/e46Hd3cDe and get the same HTML file returned. How could I achieve this in Django? If I would have to change something in the Apache config, how could I do that while testing Django locally? Currently, I test my Django website by calling python manage.py runserver and opening it at localhost:8000. -
custom reset page Django
I need some advice how to add posibility to reset password with phone number or username? my CustomUser: class CustomUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(_('username'), max_length=30, unique=True) first_and_last_name = models.CharField(_('name'), max_length=50, blank=True) email = models.EmailField(_('email address'), unique=True, blank=True, null=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") phone = models.CharField(_('phone number'), validators=[phone_regex], max_length=17,unique=True, blank=True, null=True) my urls.py: urlpatterns = [ path('accounts/', include('django.contrib.auth.urls')), ]