Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django-cors-headers does not work with Expo-web
I just ran an Expo-web development server at http://192.168.0.6:19006 and there appears many problems. When I did not install django-cors-headers, only the main page was loaded and any others requests all failed. I soon realized that I had to install django-cors-headers. So I did. But then my web app fails to stay logged in. The login process itself is successful on the server side. The client receives a messages telling that the login was successful. But when it transitioned to the next page, it automatically fell back to the main page(as I set) because the app failed to stay logged in. I am assuming that there is something wrong with cookie credentials. But I set the credentials settings like below: CORS_ORIGIN_WHITELIST = [ 'http://192.168.0.6:19006', ] CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SAMESITE = None MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] INSTALLED_APPS = [ ... 'corsheaders', ] Another issues is static files are not served with a CORS allowed header. Even if I use django-cors-headers and allow all settings, the static files fail to be loaded with an error message: Access to XMLHttpRequest at 'http://192.168.0.6:8000/static/app%20Terms%20of%20Service.json' from origin 'http://192.168.0.6:19006' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the … -
Django - cannot make url with variable in the template
I want to have a button which links to page make-appointment template.html {% for key, value in closest_free_spots.items %} ... <a href="{% url 'make-appointment' value.pk %}"><button type="button">{{ value.datetime }}</button></a> urls.py url(r'^umowienie-spotkania/(?P<pk>\d+)/$', TestPy.views.MakingAppointmentView.as_view(), name='make-appointment'), However when I try to launch it, I get error: Reverse for 'make-appointment' with arguments '('',)' not found. 1 pattern(s) tried: ['umowienie-spotkania/(?P<pk>\\d+)/$'] It looks like the value.pk is not correct, but when I print it one line above, it gives correct value (i.e. 4). What is the problem? What I'm missing? closest_free_spots definition - value is object from CalendarFreeSlot model closest_free_spots = { lawyer: TestPy.models.CalendarFreeSlot.objects.filter(Q(lawyer_id=lawyer) & Q(is_available=True)).first() for lawyer in object_list} models.py class CalendarFreeSlot(models.Model): lawyer_id = models.ForeignKey('MyUser', on_delete=models.PROTECT) datetime = models.DateTimeField() is_available = models.BooleanField(default=True) -
deploying react and django (server side) application on googlecloud
I had created a web application.Front end is created by reactjs and backend(server side)is created by django framework, Here iam using postgresql databse. The application is successfully running on my local machine by running both python manage.py runserver and npm start at a time in my terminal. I need to deploy my entire app on google cloud using compute engine. I already purchased a domain. i dont know how to connect these 2 platforms(django and reactjs) in cloud. if anyone knows deploy django as serverside and react as frontend in goolecloud (using compute engine)....please help me -
Not getting cookie value
I am trying to get cookie but it showing an error. from django.http import HttpResponse from django.conf import settings import datetime def set_cookie(response, key, value, days_expire = 7): if days_expire is None: max_age = 365 * 24 * 60 * 60 #one year else: max_age = days_expire * 24 * 60 * 60 expires = datetime.datetime.strftime(datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age), "%a, %d-%b-%Y %H:%M:%S GMT") response.set_cookie(key, value, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, secure=settings.SESSION_COOKIE_SECURE or None) def view(request): response = HttpResponse("hello") set_cookie(response, 'name', 'jujule') return response The error is: set_cookie() missing 2 required positional arguments: 'key' and 'value' -
Why is Django Postgres JSONField decoded differently depending on whether object is created or updated
I have a model with a PostGRES JSONField: from django.contrib.postgres.fields import JSONField # ... other imports ... class Feature(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # ... other fields ... meta = JSONField(default=dict) And an importer command that either creates or updates features: my_meta = { 'mykey': 'something', } feature = Feature.objects.filter(id=id).first() if feature is None: # The feature was not imported previously feature = Feature.objects.create( id=id, meta=my_meta, ) print('CREATED FEATURE.META', feature.meta, feature.meta.__class__.__name__) else: # The feature was already imported above - update the existing feature with new metadata feature.meta = my_meta, feature.save() print('UPDATED FEATURE.META', feature.meta, feature.meta.__class__.__name__) When running two different test cases, each creating one feature but testing the two branches of that 'if' statement, I get: CREATED FEATURE.META {'mykey': 'something'} dict UPDATED FEATURE.META ({'mykey': 'something'},) tuple THE QUESTION Why on earth is it decoding inside a tuple in that latter case? NOTES Yes, my default is a callable (common issue ppl have with JSONField) No, I don't have django-jsonfield installed (which can cause weird incompatibilities with the native JSONField) -
DJANGO: How to get App URLS Inside a Function?
I want to get Django Site URL's inside another function. I know and i am using, django_extensions Currently am fetching using, ./manage.py show_urls but i want fetch URLs into variable. is there a way to use django-extensions inside a custom function?