Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use Djoser with httponly cookies
I am currently building a Django-Nextjs app and I use Django build in user model and simplejwt for the tokens. I consider using Djoser to get more flexibility on the user model and a verification system, but it seems to me that I'll have to rebuild most of my authentification system. Has anyone here ever done that, and what are your thoughts? Is djoser a good choice (I am new to the authentification world ;) ? Thank you ! -
Include additional information to a File sent to Django Rest Framework
Like sait in the question. I am posting a array of files to my DRF backend. I would like to include some additional informations to some of the files being send. The simplest possible solution would be to append additional info to the file itself, although when I try attaching additional attribute to the file object in JavaScript, Python still receives the same standard TemporaryUploadedFile which does not include the additional data. Is there a reliable solution to this problem ? -
How to handle views.py after joining two models in Django?
Here I've two models first one is Contact and second model is Sent_replies. So, what should I do in views.py so that If anyone send response in Contact, the data will also update in the Sent_replies model models.py class Contact(models.Model): message_id = models.AutoField(primary_key=True) name = models.CharField(max_length=100) email = models.CharField(max_length=100) phone = models.CharField(max_length=100) comment = models.TextField(max_length=100) date = models.DateField() def __str__(self): return self.name class Sent_replies(models.Model): message_sender = models.ForeignKey(Contact,on_delete=models.CASCADE, null=True) def __str__(self): return self.message.name views.py def contact(request): if request.method == "POST": name = request.POST.get("name") email = request.POST.get("email") phone = request.POST.get("phone") comment = request.POST.get("comment") if name != "": contact = Contact(name=name, email=email, phone=phone, comment=comment, date=datetime.today()) contact.save() messages.success(request, 'Your response has been submitted successfully!!!') return render(request, 'contact.html') -
Can I deploy both python 2 django 1.9 and python 3.9 and django 3.2 apps with same apache server
i have developed one project using python 3.9 and django 3.2. and also one existing project is there that was developed python version 2 and Django 1.9.4. it was deployed in apache server it is working fine. problems are raised when we trying to deploy latest project like python 3.9 and Django 3.2 in current servers(which have already python 2 and django 1.9.4 project is running). -
Django file download 'NoneType' object has no attribute 'file'
In my website i have download button upon clicking it will download but if there is no file i get redirected to I dont want this to happen instead it should show error on page that no file or some thing like that. I have my code implemented like this views.py: @api_view(('GET',)) def temp_view(request): data = Model.objects.first() response = HttpResponse( data.file, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel', ) return response -
PUT and POST only specific fields without getting Serializer error in django
Here i wanted to post my data from thingspeak server to Django models and I have imported them by calling functions from DjangoApp.Thingspeak file.But, in this code GET and DELETE method works perfectly but, POST and PUT generates an error exception however, it also take some time for POST and PUT method too. But, as soon as I re-run my server. It catches value Immediately. Can anybody help me to debug this... Here is my code for views.py import json from django.views.decorators.csrf import csrf_exempt from django.http.response import JsonResponse from rest_framework.parsers import JSONParser from DjangoApp.serializers import PatientSerializer from DjangoApp.models import Patient from DjangoApp.Thingspeak import tempValue,humValue,bodyTempValue # Create your views here. @csrf_exempt def PatientAPI(request,id=0): if request.method == 'GET': patients = Patient.objects.all() patients_serializer = PatientSerializer(patients,many=True) return JsonResponse(patients_serializer.data,safe=False) elif request.method == 'POST': patient_data = JSONParser().parse(request) patient = Patient.objects.create(PatientId=patient_data['PatientId'],PatientName=patient_data['PatientName'],RoomTemp=tempValue(),Humidity=humValue(),BodyTemp=bodyTempValue()) patient_data = json.parse(patient) patients_serializer = PatientSerializer(data=patient_data) if patients_serializer.is_valid(): patients_serializer.save() return JsonResponse("Added Successfully", safe=False) return JsonResponse("Failed to add", safe=False) elif request.method == 'PUT': patient_data = JSONParser().parse(request) if patients_Serializer.is_valid(): patient=Patient.objects.filter(PatientId=patient_data['PatientId']).update(RoomTemp=tempValue(),Humidity=humValue(),BodyTemp=bodyTempValue()) patient = json.parse(patient) patients_Serializer = PatientSerializer(patient, data=patient_data) return JsonResponse("Updated Successfully", safe=False) return JsonResponse("Failed to Update") elif request.method == 'DELETE': patient = Patient.objects.get(PatientId=id) patient.delete() return JsonResponse("Deleted Successfully", safe=False) and Thingspeak.py code import re import urllib.request with urllib.request.urlopen("https://api.thingspeak.com/channels/1633090/feeds/last.json?api_key=C15DPT91QNH37GY6&status=true") as url: … -
New attributes are not showing up in django admin dashboard
Previously I was using my project with sqlite. Then started a new project copied the data from previous project and made some changes, and I'm using this with mysql. This is my models.py(not full) from django.db import models from django.db.models import CheckConstraint, Q, F class College(models.Model): CITY_CHOICES=[('BAN','Bangalore')] id=models.IntegerField(primary_key=True) name=models.CharField(max_length=50) city=models.CharField(choices=CITY_CHOICES,default='BAN',max_length=10) fest_nos=models.IntegerField() image=models.ImageField(default='default.jpg',upload_to='college_pics') class Meta(): db_table='college' def __str__(self): return self.name class Organizer(models.Model): id=models.IntegerField(primary_key=True) name=models.CharField(max_length=25) phone=models.IntegerField() def __str__(self): return self.name class Fest(models.Model): FEST_CHOICES=[ ('CUL','Cultural'), ('TEC','Technical'), ('COL','College'), ('SPO','Sports'), ] id=models.IntegerField(primary_key=True) name=models.CharField(max_length=50) clg_id=models.ForeignKey(College,on_delete=models.CASCADE) fest_type=models.CharField(choices=FEST_CHOICES,default='COL',max_length=10) fest_desc=models.TextField(default='This is a fest') #below two field are not showing up in admin page start_date=models.DateField(auto_now_add=True) end_date=models.DateField(auto_now_add=True) event_nos=models.IntegerField() org_id=models.ManyToManyField(Organizer) image=models.ImageField(default='default.jpg',upload_to='fest_pics') class Meta: constraints = [ CheckConstraint( check = Q(end_date__gte=F('start_date')), name = 'check_start_date', ) ] db_table='fest' def __str__(self): return self.name The start_date and end_date attributes are the new ones added in this project. It was not there in the old one. My admin.py file from django.contrib import admin from .models import College, Event, Fest, Organizer, Participated admin.site.register(College) admin.site.register(Organizer) admin.site.register(Fest) admin.site.register(Event) admin.site.register(Participated) But in my admin dashboard, while adding new fests I'm not getting the option to add start and end date. I made migrations once again, fake migrated etc. What to do? Is check constraint under model fest causing this problem? -
React + Django - Concurrent uploads are failing for large files
I am trying to do concurrent upload of chunk files from ReactJS app to Django backend. From browser I am trying to send a file(~290MB) as FormData in POST request (using axios) as chunks of 10MB. This translates to ~29 concurrent POST calls. On Client Side - ReactJS: Some of the APIs are failing (happens randomly) with status - net::ERR_HTTP2_PROTOCOL_ERROR In the Network tab in chrome, I am not able to see the payload for chunks 1 - 88 but the server is able to read these files. The payload is visible only for the 89th POST call I have tried for different chunk sizes - 10/16/32 MB On Server Side - Django: For the failed APIs, when logging the request object it says the file is missing. Any suggestions for this would be a great help -
How to fix this problem? Login if statement not working
This is my views.py def user_login(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) if user: if user.is_active: login(request, user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Your account is Inactive.") else: return HttpResponse("Invalid User Credentials Provided!!!!") else: return render(request, "MyTestApp/login.html", {}) And this is my login page: <div class="container"> <div class="jumbotron"> <h2 class="text-dark"> Login </h2> <form method="post" action="{ url 'MyTestApp:user_login '}"> {%csrf_token%} <label for="username"> Username </label> <input type="text" name="username" placeholder=" Write Your UserName Here"> <br></br> <label for="password"> Password </label> <input type="text" name="password" placeholder=" Write Your Password Here"> <br></br> <input type="submit" class="btn btn-dark" name="savebutton" value="login"> </form> </div> When I try to login it works. If I try to login with a unregistered account then it doesn't allow me returns the message "Invalid User Credentials Provided", which is good. But When I try to login with a inactive account it still returns "Invalid User Credentials Provided". It doesn't return the message "Your account is Inactive.", which it should return when I login with a inactive account. Does anyone know why this is happening. Any help will be very much appreciated. -
Expected “xref” keyword or xref stream object (line=9351, col=44, token=‘ilter’)
I got weird error like this Expected “xref” keyword or xref stream object (line=9351, col=44, token=‘ilter’) I'm trying to fill keys in a pdf via python using 'pdfrw' library. What I'm trying to do is this for page in template_pdf.pages: annotations = page[ANNOT_KEY] if annotations: for annotation in annotations: if ( annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY and annotation[ANNOT_FIELD_KEY] ): key = annotation[ANNOT_FIELD_KEY][1:-1] if key in data_dict.keys(): if type(data_dict[key]) is bool: if data_dict[key] is True: annotation.update( pdfrw.PdfDict(AS=pdfrw.PdfName("Yes")) ) else: annotation.update( pdfrw.PdfDict(V="{}".format(data_dict[key])) ) annotation.update(pdfrw.PdfDict(AP="")) template_pdf.Root.AcroForm.update( pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject("true")) ) name_of_document = "%s.%s" % ( uuid.uuid4(), output_pdf_path.split(".")[-1], ) output_pdf_path = os.path.join("media/uploads", name_of_document) pdfrw.PdfWriter().write(output_pdf_path, template_pdf) title = input_pdf_path[ input_pdf_path.rfind("/") + 1 : len(input_pdf_path) ] To clarify, this code works locally but in production no Can someone help me please? -
Elastic Beanstalk Django 502 Bad Gateway Error
Background I am currently attempting to deploy a django app on an AWS Elastic Beanstalk Environment on an Amazon Linux 2 Instance. I followed the setup instructions according to the documentation given by Amazon and I also followed other tutorials because AWS did not cover certain key points. I initially faced issues with trying to successfully deploy my Django app to my EB environment but I managed to upload my app. However, the environment now gives me a Severe health status in which when I checked eb.engine.logs I find the following error log ---------------------------------------- /var/log/web.stdout.log ---------------------------------------- web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 48, in <module> web: class AbstractBaseUser(models.Model): web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/db/models/base.py", line 108, in __new__ web: app_config = apps.get_containing_app_config(module) web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/apps/registry.py", line 253, in get_containing_app_config web: self.check_apps_ready() web: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/apps/registry.py", line 136, in check_apps_ready web: raise AppRegistryNotReady("Apps aren't loaded yet.") web: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. web: [2022-02-10 14:36:37 +0800] [20685] [INFO] Worker exiting (pid: 20685) web: [2022-02-10 06:36:37 +0000] [20678] [INFO] Shutting down: Master web: [2022-02-10 06:36:37 +0000] [20678] [INFO] Reason: Worker failed to boot. web: [2022-02-10 06:36:38 +0000] [20693] [INFO] Starting gunicorn 19.7.1 web: [2022-02-10 06:36:38 +0000] [20693] [INFO] Listening at: http://127.0.0.1:8000 (20693) web: [2022-02-10 06:36:38 +0000] [20693] [INFO] … -
Filter mongo document in django
The project stack is Django + MongoDB (djongo library). I have product table with data structure like this { _id:"qwer1234", organization:{...}, service:{ "id":1, ... } } How can I get all documents where service.id will be in array of id ([1,2,3])? -
Data truncated for column in django migrations
I had a model with a field like AGE_RANGE = ['10-20', '21-30', '31-40', '41-50', '51-60', '61-70', '71-80', '80+'] ageRange = EnumField(db_column='age_range', choices=AGE_RANGE, null=True) I just change the enum with a space inside each item AGE_RANGE = ['10 - 20', '21 - 30', '31 - 40', '41 - 50', '51 - 60', '61 - 70', '71 - 80', '80+'] When I was trying to do the migration, I am getting the following error, "Data truncated for column 'age_range' What is the solution. Thanks -
How to upload photo to the Instagram using the data from the db of django website?
I want to upload a post on Instagram from my web app . I tried creating a bot from the selenium tried connecting to my web app but it was too slow and it didn't work. Is there any to upload posts on Instagram from my own data of the web app directly? -
TypeError: QuerySet.annotate() received non-expression(s): <django.db.models.fields.IntegerField>
I'm attempting to create a custom manager method where it annotates over a QuerySet of the Tag model. The purpose of doing so is to count the number of times a tag can be found in all of the questions posted by a User. Yet, the following error is being raised: TypeError: QuerySet.annotate() received non-expression(s): <django.db.models.fields.IntegerField>. This is after getting a different error: django.core.exceptions.FieldError: Cannot resolve expression type, unknown output_field. The following link addresses the FieldError that I initially had; the answer provided didn't resolve the error as it is now raising the TypeError. I get an error when return a queryset objects: Cannot resolve expression type, unknown output_field How can this be fixed so neither error is raised? class TagManager(Manager): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def count(self, profile): user_questions = Question.objects.filter(profile=profile) return self.model.objects.filter( name__in=set(user_questions.values_list("tags", flat=True)) ).annotate(posts=Subquery(user_questions.filter( tags__name=OuterRef("name") ).count()), output_field=IntegerField()).order_by("-posts") class Tag(Model): name = CharField(unique=True, max_length=25) objects = Manager() postings = TagManager() class Meta: default_manager_name = "objects" class Post(Model): body = TextField() date = DateField(default=date.today) comment = ForeignKey('Comment', on_delete=CASCADE, null=True) profile = ForeignKey( 'authors.Profile', on_delete=SET_NULL, null=True, related_name='%(class)ss', related_query_name="%(class)s" ) score = GenericRelation( 'Vote', related_query_name="%(class)s" ) class Meta: abstract = True class Question(Post): title = CharField(max_length=75) tags = ManyToManyField( 'Tag', … -
how to run a django-upgrade command to whole django project?
I am using a library django-upgrade to convert the code from django 1.11 to django 3.24 the command is like django-upgrade --target-version 3.2 example/core/models.py I want to know that how can I run this command so that it runs on whole django project. -
Django Rest Framework viewsets.ModelViewSet
I have created a view in my DRF api that takes in a couple of parameters and saves them in the database.Am using a serializer derived from a model to do this.Below is the serializer and model code: class CreditPaymentSerializer(serializers.ModelSerializer): session = serializers.PrimaryKeyRelatedField( queryset=ShoppingSession.objects.all, many=False) class Meta: model = CreditPayment exclude = ['last_update'] and the model is class CreditPayment(models.Model): session = models.ForeignKey('shops.ShoppingSession', on_delete=models.PROTECT) name = models.CharField(max_length=50, default = 'none') number = models.CharField(max_length=15, blank=False) email = models.CharField(max_length=40, blank=True) amount_payed = models.IntegerField(blank=False) total_shopping = models.IntegerField(blank=False) amount_remaining = models.IntegerField(blank=False) date_payment_expected = models.DateField(blank=False) last_update = models.DateField(auto_now=True) def __str__(self): return self.name The viewset that is used to perform the creation of an instance of the model is: class CreditPaymentView(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] queryset = CreditPayment.objects.all() serializer_class = CreditPaymentSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) res = { "message": "Details Successfully created" } return Response(res, status=status.HTTP_201_CREATED, headers=headers) I cannot tell what is the wrong with the view,once i try to make a post request i get an error. With the error stack looking as follows Traceback (most recent call last): File "/home/sean/anaconda3/envs/skakey/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/home/sean/anaconda3/envs/skakey/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, … -
Wildcard url in Django using re_path
As per Django documentation ,below url pattern will work for http://127.0.0.1:8000/index . But I want also to make it work for http://127.0.0.1:8000/api/index/ http://127.0.0.1:8000/api/json/index/ from django.urls import include, re_path urlpatterns = [ re_path(r'^index/$', views.index, name='index'), ... ] How we can achieve it using re_path -
How to get HTML from Jquery form builder and store it in database
Iam bulding a survey website,where the user can create their own forms.My project contains 2 side , create-form where the surveyer can create the form and user side where they can fill the form , and i am using django on both sides. For starters iam using jquery form builder: <div id="fb-editor"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"> </script> <script src="https://formbuilder.online/assets/js/form-builder.min.js"></script> <script> jQuery(function($) { $(document.getElementById('fb-editor')).formBuilder(); }); </script> My plan is to take the HTML code of the generated form and store it in a database, like firebase and then re-generate the form on user-side.So i need help on how to extract the HTML of the generated form and Is it the right way to do this thing or Is there any alternative "Django" way on doing this thing. -
An error occurred during deploying code to amazon-elastic-beanstalk.error is execution of command [app-deploy] - [PreBuildEbExtension]
option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: eagle_eye.settings aws:elasticbeanstalk:container:python: WSGIPath: eagle_eye/wsgi.py -
How to pass two arguments in a url with (?P<pk>\d+)$'
In the code below referring to django's urls.py file, I'm passing the pk as an argument in the url: url(r'^data/edit_item/(?P<pk>\d+)$', edit_data, name="edit_data") I want to know if there is a way to pass two arguments in this kind of regular expression. I've tried several ways like: url(r'^data/edit_item/(?P<pk>\d+)$&header', edit_data, name="edit_data") but I'm having a lot of trouble getting the right format. The url is being called directly in the html: {% if header|lower == "specie" %} <a href="{% url 'edit_data' item.pk %}" role="button" aria-pressed="true" > Edit</a> {% endif %} So I need to pass the argument header in the html as well: {% if header|lower == "specie" %} <a href="{% url 'edit_data' item.pk header %}" role="button" aria-pressed="true" > Edit</a> {% endif %} -
Site with different authentication for site students and staff in Django?
I am trying to create a Django web app with two types of users, Students and Staff. The problem is Students must login with their full name and id number (where name is non-unique, and id number operates as password), but I do not believe there is a way for Django to allow name to be non-unique (USERNAME_FIELD constant must be unique). Staff have a different login, they can login with regular username and password (username must be unique). Also, because there are two types of users, I do not know what to put for the AUTH_USER_MODEL constant in settings.py, since there can only be one model for this. What is the best way to set up the app without running into these problems? -
How to speed up BeautifulSoup for loop
I have a for loop that parses through 6 urls to get the text of the first class with "GARawf". The loop works however I've noticed that it now takes the page about 9 seconds to load compared to 1 second before. As I am new to Django and BeautifulSoup I was wondering if there was a way I could refactor the code so it loads the view faster. views.py # create list of cities city_list = ["Toronto", "Montreal", "Calgary", "Edmonton", "Vancouver", "Quebec"] # create price list prices_list = [] # set origin for flight origin = "Madrid" #origin_urllib = urllib.parse.quote_plus(origin) # set headers headers = { "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36" } for i in city_list: # set destination for flight destination = i # set search query url = "https://google.com/search?q=" + origin + " to " + destination + " Google Flights" response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'lxml') # get price element prices = soup.find("span", attrs={"class": "GARawf"}) if prices != None: prices_list.append(prices.text.strip()) else: prices_list.append("Not Available") -
Issue with Auth0/Nginx/Django redirect after login with Nginx Proxy
I am using nginx as a proxy to pass to my django app container. I can successfully access the main url but when it passes control back to the django app and logins in the django app container gives it the local url and it doesn't route back to the correct page. The redirect uri comes in as http://app site-enabled upstream app{ server 0.0.0.0:8888; } server { listen 8080; server_name app-dev.company.net; location / { # django running in uWSGI proxy_pass http://app; include uwsgi_params; uwsgi_read_timeout 300s; client_max_body_size 320m; sendfile on; proxy_read_timeout 1800; proxy_connect_timeout 1800; proxy_send_timeout 1800; send_timeout 1800; } } docker-compose.yml version: "3.9" services: app: image: ecr/app container_name: django_app ports: - 8888 env_file: - dev.env volumes: - staticfiles:/opt/app/static/ nginx: build: ./nginx container_name: django_app volumes: - staticfiles:/opt/app/static/ ports: - 8080:8080 depends_on: - app volumes: staticfiles: -
ModuleNotFoundError: No module named 'dj_rest_auth'
I don't get why I am getting this problem I followed most the steps to the guide in installing: https://dj-rest-auth.readthedocs.io/en/latest/installation.html Except that I used pipenv install. However, python manage.py migrate gave me this error: main() File "/home/ryan/Documents/is4103/is4103-capstone-id01/Backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ryan/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 425, in execute_from_command_line utility.execute() File "/home/ryan/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute django.setup() File "/home/ryan/.local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ryan/.local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/ryan/.local/lib/python3.9/site-packages/django/apps/config.py", line 223, in create import_module(entry) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'dj_rest_auth' settings.py 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'BackendApp', 'rest_framework', 'rest_framework.authtoken', 'dj_rest_auth', ] Pipfile [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] requests = "*" django = "*" psycopg2-binary = "*" django-polymorphic = "*" pillow = "*" djangorestframework = "*" markdown = "*" django-filter = "*" dj-rest-auth = "*" [dev-packages] [requires] python_version = "3.9"