Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
jQuery AJAX works in Django server but not in Apache
I have a Django application with a form that retrieves some information with AJAX using jQuery: $('#id_doi').focusout(function() { $.ajax({ type: 'GET', url: window.location.protocol + "//" + window.location.host + "{% url 'get-doi' %}" + "?doi=" + $('#id_doi').val(), dataType: 'json', error: function (jqXHR, textStatus, errorThrown) { console.log('error ' + textStatus); }, success: function(result) { $('#id_title').val(result.title); if (result.new_journal_entry != '') { $("#id_journal").append(new Option(result.new_journal_entry, result.new_journal_id)) } $('#id_reference').val(result.this_reference); $("#id_journal").removeAttr("selected"); $("#id_journal").find('option:contains("' + result['container-title'] + '")').attr("selected", true); $("#id_pubdate").attr('value', result.issued['date-parts'][0][0]); $("#id_status").removeAttr("selected").find('option:contains("published")').attr("selected", true) } }); }) This works fine in Django server, but in Apache it gives Server Error (500) and the only thing that appears in the Apache error.log file is this table: % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 100 193 100 193 0 0 773 0 --:--:-- --:--:-- --:--:-- 775 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 100 9276 100 9276 0 0 8809 0 0:00:01 0:00:01 --:--:-- 15938 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- … -
Django 2.x Primary-Key to UUID field
I don't want my site to use integer id's as primary-key's because they are easy to determine by simyply doing i+1 instead i want to use UUID fields for that. So i started to add an UUIDField as id field on all my models like this: class User(AbstractBaseUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ... but since i did that i get errors like: Reverse for 'profile' with keyword arguments '{'pk': UUID('68065cdb-c611-4865-bffc-32e00421bef1')}' not found. 1 pattern(s) tried: ['user/(?P\d+)/profile$'] my urls.py looks like: url(r'^user/(?P<pk>\d+)/profile$', auth_required(app.view_profile_external), name='profile'), template.html: .... <div> <a href="{% url 'profile' pk=user.pk %}">My Profile</a> </div> .... do i need to change something here also? I don't get it why the UUIDField is not resolveable the same way as the Integer field as pk or id provided by django as default. -
Static files do not work in django-admin after adding Https - Django
After adding the SSL certificate, my static files do not work only in django-admin. Other files on the entire website work very well. How can I fix this situation (preferably without brutal copying of django-admin static files to my application)? urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls', namespace='app')), path('media/<path>/', serve,{'document_root': settings.MEDIA_ROOT}), path('static/<path>/', serve,{'document_root': settings.STATIC_ROOT}), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '../static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'app/media') app (/etc/nginx/sites-available/app) After making changes to this file, they django-admin static file stopped working. upstream app_server { server unix:/home/app/run/gunicorn.sock fail_timeout=0; } server { #listen 80; # add here the ip address of your server # or a domain pointing to that ip (like example.com or www.example.com) listen 443 ssl; server_name ebluedesign.online; ssl_certificate /etc/letsencrypt/live/ebluedesign.online/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/ebluedesign.online/privkey.pem; server_name 101.170.18.112; keepalive_timeout 5; client_max_body_size 4G; access_log /home/app/logs/nginx-access.log; error_log /home/app/logs/nginx-error.log; location /static/ { alias /home/app/app/app/static/; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } server { listen 80; server_name ebluedesign.online; return 301 https://$host$request_uri; } Any help will be appreciated. -
Testing a form that gets choices from database in Django - database access not allowed
I've got a test for my form that is erroring out because I have the form choices populating from a model. The error looks like this: ../myapp/tests/test_forms.py:5: in <module> from myapp.forms import AssignmentForm, AssignmentFormSet myapp/forms.py:135: in <module> class MyDetailForm(forms.ModelForm): myapp/forms.py:138: in MyDetailForm choices=[(ey.end_year, ey.full_label()) for ey in Year.objects.all()] venv/lib/python3.7/site-packages/django/db/models/query.py:268: in __iter__ self._fetch_all() venv/lib/python3.7/site-packages/django/db/models/query.py:1186: in _fetch_all self._result_cache = list(self._iterable_class(self)) venv/lib/python3.7/site-packages/django/db/models/query.py:54: in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) venv/lib/python3.7/site-packages/django/db/models/sql/compiler.py:1063: in execute_sql cursor = self.connection.cursor() venv/lib/python3.7/site-packages/django/db/backends/base/base.py:255: in cursor return self._cursor() venv/lib/python3.7/site-packages/django/db/backends/base/base.py:232: in _cursor self.ensure_connection() E Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. It appears that it doesn't like me getting the Year objects for my choices in MyDetailForm which looks like this: class MyDetailForm(forms.ModelForm): end_year = forms.ChoiceField( choices=[(ey.end_year, ey.full_label()) for ey in Year.objects.all()] ) class Meta: model = MyDetail fields = ["end_year", "is_current"] labels = {"is_current": "Current Sections"} Is this a big no-no? How do I get around this so my tests will actually run? This error pops before my tests ever run, so it's happening during my import statements. If I change [(ey.end_year, ey.full_label()) for ey in Year.objects.all()] to [] my tests run as expected, but I don't want to have to … -
Error: Uncaught SyntaxError: Unexpected end of JSON input
There is the following script. var ajax = new XMLHttpRequest(); ajax.onreadystatechange = function() { if (JSON.parse(ajax.responseText).result == 'error') { console.log('error') $.each(JSON.parse(ajax.responseText).response, function(key, value) { console.log(key) $('.contact_form_' + key).css('display', 'block') $('.contact_form_' + key).prev().css("border", '1px solid #FD7900') $('.contact_form_' + key).text(value) }) } else { location.reload(); } } It is intended for an ajax request to the server. In response, from the server I pass json with the data. Empty json may come. I get the following error. Uncaught SyntaxError: Unexpected end of JSON input Swears at this line - if (JSON.parse (ajax.responseText) .result == 'error') { Json examples that may come if contact_form.is_valid(): contact_form = contact_form.save() return JsonResponse({}) else: response = {} for k in contact_form.errors: response[k] = contact_form.errors[k][0] return JsonResponse({"response": response, 'result': 'error'}) -
How to custom django-filter form?
How to custom django-filter form? I want add onChange="form.submit();" and to set labels in template. When I tried to use {{ filter.age_filter }} in template it doesn't show anything. My filter: class EventFilter(django_filters.FilterSet): AGE_CHOICES = ( ('18+', '18+'), ('19+', '19+'), ('21+', '21+'), ) age_filter = django_filters.ChoiceFilter(label='Age Limit', choices=AGE_CHOICES, method='filter_by_age') class Meta: model = Event fields = {'title': ['icontains']} def filter_by_age(self, queryset, name, value): return queryset.filter(age_limit=value) My template: <form method="get" > {{ filter.form}} <button type="submit" class="btn btn-sm btn- primary">Filter</button> </form> -
How to change base url of axios after have build vue-cli 3 project
I am in the process of putting into production a web application (back: django rest framework, front: vue-cli3) But my deployment environment is very specific. I have an embedded card on which a linux is deployed. This card runs in a local area network and its IP address is managed via DHCP from the router. On this card there is the django server and a nginx to manage the build of Vuejs app. My problem is to modify the base url Axios (it's make the HTTP request between vue.js and my server)with the IP address of the card so that the vuejs application on the client can communicates with the back which is on the card. So do you know a way to change the base_url of Axios after the build of vue js ? Thanks in advance ! And sorry for my pitiful english, I'm french I test to put in other file (conf.json) my address ip which i can change with python file if the DHCP send me a new IP address but it's don't work. I test with the hostname of the card but in windows computer the zeroconf can work without install software like Avahi in … -
Is it possible to do partial template rendering in Django?
I wonder if it's possible to partial render Django template. Let me make it clear what I want, please check this out (this is in django shell python manage.py shell, not in basic python shell): from django.template import Context, Template t = Template('{{var1}} - {{var2}}, {% if var2 %} {{var2}} {% endif %}') t.render(Context({'var1': 'test'})) output: 'test - ,' But I wonder, if it's possible to render only passed variables, so my desired output is 'test - {{var2}}, {% if var2 %} {{var2}} {% endif %}' I want to get it, because I didn't pass var2. I know there is a string_if_invalid setting, but it's only for debug purpose. -
CSRF verification failed error with react, axios and DRF
I am trying to make a post request which looks like this axios .post(`http://127.0.0.1:8000/api/create/${this.props.id}`, { headers: { Authorization: `Token ${token}` }, xsrfCookieName: "csrftoken", xsrfHeaderName: "X-CSRFToken" }) .then(); I have added essential things in settings.py also, such as CSRF_COOKIE_NAME = "XSRF-TOKEN" I also have REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.BasicAuthentication', ), } -
Case Insensitive Query Filtering in Django
I have a query filter which is case sensitive. For example, ?search_query=Atl returns "Atlanta" while ?search_query=atl returns no matches. How can I make my filter case insensitive? views.py filtered_objects = Opportunity.objects.filter(companyId__icontains=term) & Opportunity.objects.exclude(status='Opportunity Created') -
Stop Django server without control key
I need to kill the Django development server from a shellscript in linux. How can this be done, since the shell script can't hold the 'CONTROL' key? Is there sytnax that performs the same function? I tried: $CONTROL-C $^C $SIGINT -
How to change 'localhost' url django
I want to play around with social-django authentication app. Iwant to add for login with facebook. For that I need to change my 127.0.0.1 to something like my-site.com. I wanted to change /etc/hosts, unfortunetely it doesn't exist. I created hosts file using touch command and added 127.0.0.1 my-site.com (nothing more) and restarted my computer. I tried runserver command and copy-pasted hostname above to the beggining of the link (my-site.com:8000) but it didn't work. My django project runs on venv. If you have any ideas on solving my problem, please share (I've posted a similar question on superuser.com, but no one seemed to know a solution there, so I ask here) -
Getting |as_crispy_field got passed an invalid or inexistent field
Im using crispy field on inputs for css speed. I have my {{from.username|as_crispy_field}}. When i submit the data i get a CrispyError at /client error. Exception Type: CrispyError Exception Value: |as_crispy_field got passed an invalid or inexistent field What do i need to do to handle this in views ? -
Remove 4xx handled errors from new relic Django project
I am looking at a way to remove 4xx errors from my newrelic error rate reporting for a Django project. It's a standard installation of new relic and Django framework. Any help appreciated for same. -
Flutter app with Django backend and google authentication
i would like to create a flutter app, with social authentication (Facebook & Google) connected to a Django DRF backend. I could not find any examples for handling the social authentication at the back-end coming from a flutter app, i only found firebase based tutorials. Any libraries that work this way? in case there aren't, how could i send the required social account from the phone to my backend? Thanks!! -
Graphene errors messages
I wonder if it is possible to translate the validation error messages that graphene provides? For example: "Authentication credentials were not provided" as shown in the code example below. { "errors": [ { "message": "Authentication credentials were not provided", "locations": [ { "line": 2, "column": 3 } ] } ], "data": { "viewer": null } } -
Select buttons in javascript when used in django templates forloop
I have table in html <tbody> {% for item in cartitems %} <tr> <th scope="row">{{forloop.counter}}</th> <td>{{item.name}}</td> <td id="counter"> <button id='minusButton' class="btn btn-default btn-xs"> <i class="fas fa-minus mr-2"></i> </button> 1 <button id='plusButton' class="btn btn-default btn-xs"> <i class="fas fa-plus ml-2"></i></td> </button> <td>{{item.price}}</td> </tr> {% endfor %} </tbody> I want to increment and decrement text in second td which is 1 right now by clicking on plus, minus button I wrote this javascript but it only works for the first loop of buttons. var plusButton = document.getElementById("plusButton") var minusButton = document.getElementById("minusButton") let counter = 1; plusButton.onclick = function(){ counter ++ this.parentElement.childNodes[2].nodeValue = counter } minusButton.onclick = function(){ counter -- this.parentElement.childNodes[2].nodeValue = counter } I expect all buttons to select and increment and decrement their respective td text -
How to relate checkBoxes with customized actions?
i have written custom action (command) in django admin template. when i choose checkbox, i want to have IP of that row in response when i click custom action. -
How to make import-export save JSONField not as string
I'm trying to import JSONField using django import-export, it keeps saving JSON as string (adding "" to it) models.py from django.db import models from django.contrib.postgres.fields import JSONField class Governorate(models.Model): name = models.CharField(max_length=500) data = JSONField() def __str__(self): return ("%s" %(self.name)) admin.py from django.contrib import admin from .models import Governorate from import_export.admin import ImportExportModelAdmin from import_export import resources class GovernorateResource(resources.ModelResource): class Meta: model = Governorate class GovernorateAdmin(ImportExportModelAdmin): list_display = ('id','name', 'data') resources_class = GovernorateResource admin.site.register(Governorate,GovernorateAdmin) I expected the output to be: {"xx":{"xx":"xx","xx":"xx"} however it saves it as "{"xx":{"xx":"xx","xx":"xx"}" Tried uploading XLSX and CSV. -
'FieldFile' object has no attribute 'full_clean' - even though it should work in my opinion
I've been trying to implement a file size validator in django on a filefield, but I can't really make it work. Everything works right until I add this validator. After I add it, I can't upload files anymore at all. The error says "File field does not have a full_clean attribute". views.py from django.shortcuts import render, get_object_or_404 from .models import Oferta, CV from django.contrib import messages from django.core.paginator import Paginator def incarcarecv(req): context = { 'title': "Incarcare CV | Best DAVNIC73" } if req.method == 'POST': nume = req.POST['nume'] prenume = req.POST['prenume'] telefon = req.POST['telefon'] email = req.POST['email'] cv = req.FILES['CV'] if(req.user.is_authenticated): cv_upload = CV( solicitant=req.user, nume=nume, prenume=prenume, telefon=telefon, emailContact=email ) cv_upload.CVFile.full_clean() cv_upload.CVFile.save(cv.name, cv) cv_upload.save() req.user.profile.cvuri.append(cv_upload.id) req.user.profile.save() messages.success(req, 'CV depus cu succes!') else: messages.error(req, 'Trebuie sa fii logat pentru a depune CV-ul!') return render(req, "../templates/pagini/incarcare-cv.html", context) models.py from django.db import models from django.contrib.auth.models import User from .validators import validate_file_size # Create your models here. class Oferta(models.Model): solicitant = models.ForeignKey(User, on_delete=models.CASCADE) dataSolicitare = models.DateField(auto_now_add=True) cor = models.CharField(max_length=25) denumireMeserie = models.CharField(max_length=12) locuri = models.IntegerField() agentEconomic = models.CharField(max_length=50) adresa = models.CharField(max_length=150) dataExpirare = models.DateField() experientaSolicitata = models.CharField(max_length=200) studiiSolicitate = models.CharField(max_length=200) judet = models.CharField(max_length=20) localitate = models.CharField(max_length=25) telefon = models.CharField(max_length=12) emailContact = models.EmailField(max_length=40) rezolvata … -
Django, check if exists but on many items from an array of properties
arr = [ {id: 1, filename: "a"}, {id: 2, filename: "b"}, ] If I wanted to check if a Django table has 2 items with properties corresponding to the above, I could do: for n in arr: e = MyTable.objects.filter(id=n["id"], filename=n["filename"]).exists() if not e: # raise error But this requires to do one query for each item in the array. How can I do this in a single query? I was thinking to chain Qs like this: Q(id=n['id'],filename=n['filename']) | Q(id=n['id'],filename=n['filename']) | ...for each item in array But then how I could I check if each separate Q returns at least one entry? -
How to disable Django-OTP / Double Authentification / 2FA
If you have lost your access to your website and can't use 2FA that is activated on your Django with django-otp plugin, comment that line in your urls.py : admin.site.__class__ = OTPAdminSite To : # admin.site.__class__ = OTPAdminSite After, try to login without 2FA, get your QRCode and uncomment the line to enable the double-authentification. -
The type of a variable
I have to get the type of a variable and when I type type(variable) I get this : <class 'Mytable.models.User'> And I would like to equal the type of a variable I mean I try to write this : type(variable) == Mytable.models.User but I got False. Could you help me please ? -
Django Channels Business Logic
I am currently making a game in real-time using Django channels, but I am a little bit confused about where the Business Logic should go.. Considering that we have to use the "database_sync_to_async" decorator for async consumers, where should we put the logic? -
Django not loading static files into assets file
I recently started a basic django project, i want to load an already made default template. This template has an assets folder with all the CSS, JS files etc This folder, is later called in the templates, so for example i can have: <base href="../"> // And a lot of static files being called like this: <link href="./assets/scrollbar/css/scrollbar.css" rel="stylesheet" type="text/css" /> <link href="./assets/somecss.css" rel="stylesheet" type="text/css" /> // And so on.. The problem with this is that none of the files in the assets are being retrieved. I know that the problem depends on where i put the assets folder, but i don't know how to solve that. I tried to add it to different parts of my project's structure but it doesn't work, since i only get a lot of errors like this: http://127.0.0.1:8000/assets/somecss.css net::ERR_ABORTED 404 (Not Found) Here is my settings.py: STATIC_URL = '/static/' In this static folder, there is a basic css file i tested before trying this. And here is the structure of my project: //MAIN FOLDER migrations ASSETS templates -> INDEX.HTML (where the assets folder is called) views, forms etc