Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot assign requested address: when sending e-mail from Django Docker container
I have this error message, when sending an e-mail from Django Docker container. OSError at /accounts/signup/ [Errno 99] Cannot assign requested address Request Method: POST Request URL: http://127.0.0.1:8000/accounts/signup/ Django Version: 4.0.10 Exception Type: OSError Exception Value: [Errno 99] Cannot assign requested address Exception Location: /usr/local/lib/python3.10/socket.py, line 833, in create_connection Python Executable: /usr/local/bin/python Python Version: 3.10.4 Python Path: ['/code', '/usr/local/lib/python310.zip', '/usr/local/lib/python3.10', '/usr/local/lib/python3.10/lib-dynload', '/usr/local/lib/python3.10/site-packages'] Here is my configuration in settings.py EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" DEFAULT_FROM_EMAIL = "my@gmail.com" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_USE_TLS = False EMAIL_HOST_USER = "my@gmail.com" EMAIL_HOST_PASSWORD = "mypassword" Here is docker-compose.yml. version: "3.9" services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db environment: - "DJANGO_SECRET_KEY=my_key" - "DJANGO_DEBUG=True" db: image: postgres:13 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - "POSTGRES_HOST_AUTH_METHOD=trust" volumes: postgres_data: I'm able to send e-mail with the same config via Python code without docker container. -
webrtc shows extra stream with only one peer connection
I am trying to allow my webrtc video call meeting app have multiple peer connections and have the stream appear on the remote video call dynamically using javascript. I have only two tabs in two windows open on the video test room url. One is incognito and one is regular google chrome browser but both are google chrome browsers. They are both logged in to superusers. The problem is, the remote videos are shown twice of the same user of the remote user. This is my video call html file. <!DOCTYPE html> <html> <head> <style> button { border: 0; background-color: orange; padding: 10px; color: white; border-radius: 7px; } video { border-radius: 15px; } .videoContainer { display: flex; margin: 20px; width: 640px; } .videoContainer h2 { color: white; position: relative; bottom: -380px; left: -350px; width: max-content; } #meet { display: flex; } #recordButton.recording { background-color: red; } #downloadButton { background-color: #4caf50; } button:disabled { background-color: #cccccc; cursor: not-allowed; } </style> <title>A Free Bird Video Call</title> <script src="https://meet.jit.si/external_api.js"></script> </head> <body> <div id="meet"> <div id="remote-videos"> <div class="videoContainer"> <video id="localVideo" autoplay playsinline></video> <h2>{{ request.user.full_name }}</h2> </div> </div> <!-- <div class="videoContainer"> <video id="remoteVideo" autoplay playsinline></video> <h2></h2> </div> --> </div> <div> <button onclick="startCall()">Start Call</button> <button id="recordButton" … -
Google OAuth 2.0: Login with Google works on localhost, but it doesn't work on hosting
I have a small Django website, and I've connected OAuth 2.0. It worked just fine on localhost. (In the Google Console, the authorized redirect URIs were: URI 1: http://127.0.0.1:8000/ URI 2: http://127.0.0.1:8000/google/login/callback/) Now I have moved the website to hosting and changed the URLs to: URI 1: https://yukkiewqr.eu.pythonanywhere.com/ URI 2: https://yukkiewqr.eu.pythonanywhere.com/google/login/callback/ However, when I'm trying to log in through Google, I see the following error: "Access blocked: This app’s request is invalid. You can’t sign in because this app sent an invalid request. You can try again later or contact the developer about this issue. Learn more about this error. If you are a developer of this app, see error details. Error 400: redirect_uri_mismatch." On my website, I am using the Django Framework and the AllAuth plugin to connect to Google. I would be very grateful if anyone knows how to fix it -
Why is my email template in Django sending the whole model and not just the values input
I'm trying to email a copy of my contact form when the form is saved, but the template tags seem to be pulling the full model not just the inputs. I have no idea what I'm doing wrong here. My email template.txt file Hi! You received a message from {{ contact_form.name }} at {{ contact_form.email }} {{ contact_form.message}} My views.py if request.method == "POST": contact_form = ContactForm(request.POST, request.FILES) if contact_form.is_valid(): contact_form.save(commit=False) try: contact_form.image_field_1 = request.FILES['image_field_1'] except: contact_form.save() try: contact_form.image_field_2 = request.FILES['image_field_2'] except: contact_form.save() contact_form.save() subject = 'Website enquiry' body = render_to_string( 'contact_emails/contact_email_body.txt', {'contact_form': contact_form, }) send_mail( subject, body, settings.DEFAULT_FROM_EMAIL, ['test@gmail.com'], ) messages.success(request, "Message received! \ We will respond as soon as possible!") else: contact_form = ContactForm() This is what arrives in the email Hi! You received a message from at Testing again -
Asyncio coroutine execution stopped and didn't return any error
I'm facing an odd behavior on one of my applications. So I have an application that has an POST entrypoint that receives a list of order id's and after processing each order it must inform an external API about the monetary value of each order. So what we did was the following: round_details_tasks = [ asyncio.create_task( self.launch_individual_order_details(order), name=f"task_order_{order.id}", ) for order in active_orders ] results = await asyncio.gather(*order_details_tasks, return_exceptions=True) for task, result in zip(order_details_tasks, results): if isinstance(result, Exception): print(f"⚠️ Task '{task.get_name()}' raised an exception: {result}") else: print(f"✅ Task '{task.get_name()}' succeeded with result: {result}") The launch_individual_order_details(order) function does the following stuff and other non I/O logic before this block: logger.debug(f"Sending order details with success for order: {order.id}") await order_service.send_order_request(order) Inside send_order_request we create a entry on a table called Transaction with the order id and the corresponding order amount and in pending state and send http request using aiohttp.CLient library. Afterwards we update the transaction status to Success if the request response is succesful and to error if the request fails. So the problem we are facing is that when our system is with a relative amount of load in our pods when the pod uses 70% of the CPU limits … -
User getting added to multiple permission groups instead of the one
In my application, when a user registers, they are identified as either a lecturer or a student. These are categorised as auth_groups, and users are assigned to one with these methods... def register_student(self, data): user = User.objects.create( user_id = data["user_id"] ) students_group = Group.objects.get(name = "students") user.groups.add(students_group) return user def register_lecturer(self, data): user = User.objects.create( user_id = data["user_id"] ) lecturers_group = Group.objects.get(name = "lecturers") user.groups.add(lecturers_group) return user On the surface, this appeared to work fine, but when I went to write the test suite, the following issue occurred: When register_student is called, the user is added to both the lecturer and student groups in the line user.groups.add(students_group). I want to mention that "students" have more permissions than "lecturers". Why is this happening? Thank you for any help! -
How to Restart a Django App via API After Modifying settings.py?
I am working on a Django project where I dynamically add new languages via an API. The workflow is as follows: Add a new language via the API (http://localhost:8000/core/swagger/). Via API /generate/ Generate the .mo and .po files after adding the language. The new language is added to languages.json, which is loaded into settings.py at startup. To apply the new language, Django needs to be restarted. I have tried several approaches to restart Django automatically via an API: ✅ Clearing Django's cache before restarting. ✅ Using a .sh script to kill the process and restart Django. ✅ Manually stopping and restarting Django (this works fine manually, but not via the script). Issue: When calling the restart API, Django stops successfully but does not restart. The restart only works when I manually stop the server and restart it from the terminal. The script kills the PID but doesn’t properly relaunch Django. What I Need Help With: What is the best way to restart Django from within an API call? Is there a more reliable way to restart Django inside Docker as well? Why does manually stopping Django and then restarting work, but the script approach does not? Relevant Repo with explaination … -
Django - PostgreSQL docker - authentication issue
I've been trying to set up my first Django and PostgreSQL project with Docker containers. I followed this setup and everything went as expected: https://learndjango.com/tutorials/django-docker-and-postgresql-tutorial Opening my Django admin portal worked without any issues on: http://127.0.0.1:8000/admin/ However I also wanted to connect to my 'db' (via DBeaver or in the terminal). However, I keep getting this error: FATAL: password authentication failed for user "postgres" FATAL: password authentication failed for user "postgres" Does anyone have any experience with this issue? DBeaver connection docker-compose.yml settings.py I first tried to only have my PostgresQL database in docker and keep the Django project outside, locally. However, that was the first time I bumped into the issue of 'password authentication'. I figured it was because I didn't set up both the Django project and my PostgresQL in Docker containers. But unfortunately, adding both in Docker containers did not help. I also tried to: Change the pg_hba.conf authentication Method to 'host all all all md5' instead of 'host all all all scram-sha-256'. But that didn't do anything either. -
heroku django Spatilite Unable to load the SpatiaLite library extension
Hi I get error while i'm trying to run my application on heroku with Spatialite: Unable to load the SpatiaLite library extension. Library names tried: mod_spatialite.so, mod_spatialite. my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # 'ENGINE':'django.contrib.gis.db.backends.postgis', # 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } django_heroku.settings(locals()) # geodjango=True if DATABASES['default']['ENGINE'] in ('django.db.backends.postgresql', 'django.db.backends.postgresql_psycopg2'): DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.postgis' elif DATABASES['default']['ENGINE'] == 'django.db.backends.sqlite3': DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.spatialite' -
Wagtail admin preview panel not working in production
The page preview in the Wagtail admin is working fine locally on my dev server, but in production, the preview is not displayed, just a spinning wheel. In the Chrome dev tools console, I see the error message: Uncaught SecurityError: Failed to read a named property 'scroll' from 'Window': Blocked a frame with origin "https://example.com" from accessing a cross-origin frame. where I replaced my actual domain by "example.com". In production, I'm using Wagtail 6 with nginx and gunicorn, serving media and static files from the same server. Here are the relevant parts of my nginx config, with some data XXXXed out: upstream app_server { server unix:/opt/example-com/gunicorn.socket fail_timeout=0; } server { listen 80; server_name example.com; rewrite ^/(.*) https://example.com/$1 permanent; } server { listen 443 ssl; server_name example.com; client_max_body_size 50M; ssl_certificate XXXX ssl_certificate_key XXXX location /static/ { alias /opt/example-com/static/; } location /media/ { alias /opt/example-com/media/; } location / { include proxy_params; proxy_pass http://unix:/opt/example-com/gunicorn.socket; } location /admin/ { include proxy_params; proxy_pass http://unix:/opt/example-com/gunicorn.socket; } } In the base settings, I have set WAGTAILADMIN_BASE_URL = "https://example.com" and on /admin/sites/, the have set the site hostname to "example.com". I'm not sure why I'm running into this cross-site thing at all, and how to fix it. -
BooleanField form Checkboxes always empty in Django
I have a Model form that has some checkboxes. The database has values for these records for all rows. My form displays with empty checkboxes all the time. I can submit values via the checkbox and the database updates correctly, but form still shows empty checkboxes. What am I missing here? Model definition contains is_coach = models.BooleanField(default=False, blank=True) is_parent = models.BooleanField(default=False, blank=True) is_committee = models.BooleanField(default=False, blank=True) Form is forms.ModelForm containing is_committee = forms.BooleanField(required=False) is_coach = forms.BooleanField(required=False) is_parent = forms.BooleanField(required=False) HTML template contains <form action="{% url 'user_profile_admin' %}" method="post"> {% csrf_token %}{{ form|crispy}} <button type="submit" class="btn btn-success">Update</button> <button type="button" onclick="window.location='members';return false;"class="btn btn-danger">Cancel</button> </form> Link to screenshot showing checkboxes -
Django Returning http instead of HTTPS in Prod
I deployed a Django app in an Ec2 with gunicorn and nginx but links generated by django are http instead of HTTPS. I have included the necessary settings. For example, when I have paginations, I got count": 12, "next": "http://my.example.com/article/?page=2", "previous": null, Instead of count": 12, "next": "https://example.com/journal/?page=2", "previous": null, All the links are like this, although they got redirected when you click on them or copy them in the browser but it is showing a funny reaction in the frontend My DNS is being managed by cloudfare and everything seem to be fine there. #In settings SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') USE_X_FORWARDED_HOST = True #My nginx file server { listen 80; server_name fronend.example.com; location / { autoindex on; root /home/ubuntu/frontend/dist/frontend; try_files $uri $uri/ /index.html; } } # Backend Nginx Config server { listen 80; server_name backend.example.com; location = /favicon.ico { access_log off; log_not_found off; } location /staticfiles/ { alias /home/ubuntu/backend/static; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; # proxy_set_header Host $host; #I commented these out when I was troubleshootng # proxy_set_header X-Real-IP $remote_addr; # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/backend.example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/backend.example.com/privkey.pem; # managed by … -
Embedding a Web Application Using an Iframe
I have a Django application (A), and one of my clients wants to embed it within their application (B) using an iframe. The client application can be built with any framework, and we have no control over its code. Additionally, both applications are hosted on entirely different domains. To enable this setup, we need to fine-tune the settings in our Django application A to allow embedding within client application B. Below is a test HTML code snippet used to embed the web application, which I have hosted using a free hosting service. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>URL Loader</title> <style> body { font-family: Arial, sans-serif; text-align: center; margin: 20px; } iframe { width: 100%; height: 80vh; border: 1px solid #ccc; } </style> </head> <body> <h2>Loaded URL in iFrame</h2> <iframe id="urlFrame" src="https:/xyz.com" ></iframe> </body> </html> Django Configuration: Python 3.6 Django: 2.2.5 Changes made: Updated Django settings to permit the domain to load the application. Some of the settings below should be hardened for security in production, as they are intended only for POC purposes.: DEBUG = True Removed X_FRAME_OPTIONS = "DENY" and used CSP_FRAME_ANCESTORS = ("'self'", "*") CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CSRF_TRUSTED_ORIGINS = … -
How To Append & Send File data in a multipart react form with Django backend with Nested JSON
So, I have a form data with the corresponding JSON format project_status: 'OPEN', project_title: '', project_code: '', start_date: '', end_date: '', duration: '', engagement_year: '', financial_year: '', project_budget: '', domain: '', project_type: '', project_mou: null, other_docs: null, thirdAgencyDetails: { government_body: '', scheme_name: '', sanctioned_budget: '', industry_contribution: '', government_contribution: '', agreement: null, sanction_letter: null, proposal_doc: null }, facultyDetails: [], I trying to send this data to Django backend which has the following model class Project(models.Model): user = models.CharField(max_length=15, null=True) project_title = models.CharField(max_length=250, null=True) project_code = models.CharField(max_length=250, null=True) start_date = models.DateField(max_length=10, null=True, default='') end_date = models.DateField(max_length=10, null=True, default='') duration = models.CharField(max_length=255) engagement_year = models.IntegerField() financial_year = models.CharField(max_length=255) project_budget = models.DecimalField(max_digits=10, decimal_places=2) domain = models.CharField(max_length=250, null=True) project_type = models.CharField(max_length=255) project_status=models.CharField(max_length=250, blank=True) thirdAgencyDetails = models.OneToOneField(ThirdAgencyDetail, on_delete=models.CASCADE, null=True, blank=True) project_mou = models.FileField(upload_to='R&D_docs/', blank=True) other_docs = models.FileField(upload_to='R&D_docs/', blank=True) with a one to one field to class ThirdAgencyDetail(models.Model): government_body = models.CharField(max_length=255) scheme_name = models.CharField(max_length=255) sanctioned_budget = models.DecimalField(max_digits=10, decimal_places=2) industry_contribution = models.DecimalField(max_digits=10, decimal_places=2) government_contribution = models.DecimalField(max_digits=10, decimal_places=2) agreement = models.FileField(upload_to='jointProject_thirdAgency_docs/',blank=True) sanction_letter = models.FileField(upload_to='jointProject_thirdAgency_docs/',blank=True) proposal_doc = models.FileField(upload_to='jointProject_thirdAgency_docs/',blank=True) I have written a form uploading code refer code gist here I am unable to append the files for 'thirdAgencyDetails' since it is a nested JSON in similar manner to if (formData.project_mou) … -
Prevent Multiple Users from Booking the Same Table at the Same Time in Django
I have a Booking model where users can book a restaurant table for a specific date and time. However, I want to ensure that multiple users cannot book the same table at the same time. Here’s my model: class Booking(TimeStampWithCreatorModel, TerminalMixin, SoftDeletableModel): table = models.ManyToManyField(RestaurantTable, related_name="booking_table") customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="booking_customer") no_of_people = models.IntegerField() booking_date = models.DateField() booking_time = models.TimeField(null=True, blank=True) note = models.TextField(blank=True) accept_terms_and_conditions = models.BooleanField(default=False) receive_emails = models.BooleanField(default=False) class Meta: ordering = ("-created",) What I've Tried I attempted to use select_for_update to lock the rows while making a booking, but when multiple users try to book the same table at the exact same time, duplicate bookings are still created in some instances. Here’s the approach I used: from django.db import transaction def create_booking(customer, table_ids, booking_date, booking_time, no_of_people): with transaction.atomic(): tables = RestaurantTable.objects.filter(id__in=table_ids).select_for_update() if Booking.objects.filter(table__in=tables, booking_date=booking_date, booking_time=booking_time).exists(): raise ValueError("Table already booked for this time slot.") booking = Booking.objects.create( customer=customer, no_of_people=no_of_people, booking_date=booking_date, booking_time=booking_time ) booking.table.set(tables) return booking The Problem Despite using select_for_update, when multiple instances try to book at the same time, the check Booking.objects.filter(...) does not prevent race conditions properly. I assume this happens because Django’s ManyToManyField does not lock relationships the same way ForeignKey does. Expected Outcome Prevent … -
Create a Mock Request for django rest framework
I am trying to createa mock Request for a post method in django rest framework and tried: factory = APIRequestFactory() data = {"hello": 1} print(data) django_request = factory.post(url, data, format="json") print("body:", django_request.body) print("ct:", django_request.content_type) r = Request(django_request) print(r.data) The printing correctly shows the body to be set to a (binary) string. However the final r.data is an empty list. How do I set the data? -
Django css not rendering in Production
In my Django5 app everything works fine in development under venv but once I load the application into a Docker container with Debug=False I don't seem to get my CSS rendered properly. Whats really wierd is the CSS loading appears to be correct, I just don't get my custom css hero image and colors, and the admin css is also broken. I'm using gunicorn with nginx serving static data. I do see my favicon.ico which is served from the same /static/ folder and the css, js, etc. folders all exist in the nginx container as expected. I view source and click on the links and they're all there. In Django settings.py I have: from pathlib import Path import os import environ env = environ.Env( DEBUG=(bool, False) ) BASE_DIR = Path(__file__).resolve().parent.parent environ.Env.read_env(os.path.join(BASE_DIR, '.env')) SECRET_KEY = env('SECRET_KEY') DEBUG = env('DEBUG') ALLOWED_HOSTS = ['*'] . . . STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Changing STATIC_ROOT to the actual container path '/usr/share/nginx/html/static/' didn't change the behaviour. In my root urls.py: urlpatterns = [ path("admin/", admin.site.urls), . . . ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My dockerfile-compose.yaml includes collectstatic: web: build: context: . dockerfile: Dockerfile command: > sh -c "python manage.py collectstatic --noinput && python manage.py … -
How to disable the options in select with Django
I created a calendar with dates where appointments can be made. I then created a form to select appointments. I want each time an appointment is made, it to be grayed out for the exact day and time it was made. For March 2, 2025 I booked an appointment at 9am, for January 24, I booked an appointment at 8am and for March 6, 2025, I booked an appointment at 2:15pm. However, as you can see in the picture, when I click on March 2, 2025, the times 8am, 9am and 2:15pm are all grayed out even though I used them for different days. Thanks in advance #********************************** def formatday(self, day, rdvs): select_hour = RdvForm() select_dat = Rdv.objects.all().values() p = len(select_dat)`enter code here` rr =len(select_hour['start_time']) ls_h = [] ls_d =[] ls_dd=[] # add value in list for i in range(p): ls_h.append(select_dat[i]["start_time"]) for lis_d in range(p): f = str(select_dat[lis_d]["select_date"]) ls_d.append(f[:7]) #list day year for dd in range(p): ff = str(select_dat[dd]["select_date"]) ls_dd.append(int(ff[8:])) year_month_curent =str (self.year)+'-'+str("{:02}".format(self.month)) htm = f'<select name="start_time" id="id_start_time">' for i in range(rr): if select_hour['start_time'][i].data['value'] in ls_h and year_month_curent in ls_d and day in ls_dd: htm+= f'<option class="{i}" disabled="disabled" value="{select_hour['start_time'][i].data["value"]}">{select_hour['start_time'][i].data["value"]}</option>' else: htm+= f'<option value="{select_hour['start_time'][i].data["value"]}">{select_hour['start_time'][i].data["value"]}</option>' htm+=f'</select>' #***************** for i in range(rr): if … -
Exception when trying to launch django project debug in VS code
Hi I have a django project (4.2.2) and when I start the project from the terminal inside VS Code using "python3 manage.py runserver" everything works perfectly. But I want to debug it so I created a launch.json file to start it as debug Here is what it contains: { // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ { "name": "Python Debugger django", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}/manage.py", "console": "integratedTerminal", "django": true, "args": [ "runserver", ] } ] } When I try to start the project using debug button I get the following error: django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 or psycopg module I have installed psycopg library as if I look at my requiremnts.txt I have psycopg==3.2.4 psycopg-binary==3.2.4 Not sure what is the problem? In debug mode the error is display in my models.py file: from django.db import models class User(models.Model): # <-- here is the error """ User entity """ id = models.AutoField(primary_key=True) first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=100) # created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.first_name} {self.last_name}" -
Manually access content from Form fields in Django
I'm in a position where I would like to submit content to a form that is not defined in a Forms class. For example, in my forms.py: class AnalyseForm(forms.Form): TYPES = (('a', 'Type A'),('b', 'Type B'), ('c', 'Type C')) filename = forms.FileField(label="Document to Aalyse") doctype = forms.ChoiceField(choices=TYPES, label="Doc Type:") and in my views.py: I am trying to send an additional variable that doesn't exist in the Form class, because I defined it in the HTML file manually. The answer to this isn't 'define it in the Form class. I have for example other HTML widgets that are to going to play with being shoehorned into a Django Form definition. def AnalyseDoc(request): doctype="" if request.method == "POST": form = AnalyseForm(request.POST, request.FILES) if form.is_valid(): filecontent = request.FILES['filename'] doctype=form.cleaned_data['doctype'] # dummydata=form.cleaned_data['dummydata'] print(dummydata) analyse = analyseStuff(file=filecontent,doctype=doctype, dummydata=dummydata) else: form = AnalyseForm() return render( request, "summary.html", { "dummydata": "x", "form": form, 'filecontent': filecontent, "doctype": doctype, }, ) This is a bit of a quandry <h1>What file would you like to Analyse?</h1> <form action = "" method = "post" enctype="multipart/form-data"> <div class="form-check form-switch"> <label class="form-check-label" for="dummydata">Use Dummy Data</label> <input class="form-check-input" type="checkbox" role="switch" id="dummydata" checked> </div> {% csrf_token %} {{form | crispy}} <button id="submit" type="submit" class="btn btn-primary">Analyse<button> … -
How to Implement Media File Upload Limits and Through Models in Django API for Large Real Estate File Management System?
I am building a large real estate file management system using Django API. I have created a separate app for media handling, and in my model, I want to enforce the following limits: A single featured image A gallery with a maximum of 10 images A maximum of 2 video uploads, each with a cover image A maximum of 2 music files A maximum of 2 PDF files For these, I've used a Through Model to connect the media model to the main model, such as a "listing" or "project" model. My question is: Should these upload limits be handled within the Django serializer, or is there a better approach? Is this the best way to connect models, especially when the main models might have multiple foreign keys? I’m concerned about performance and scalability. Since speed is critical and I need to connect media to models across multiple apps, what would be the most efficient way to implement these restrictions? Thanks in advance! my code : Model.py from django.db import models from django.core.validators import FileExtensionValidator import os from django.utils.translation import gettext_lazy as _ import uuid from django.core.exceptions import ValidationError from src.core.models.base import BaseModel def upload_media_path(instance, filename): ext = filename.split('.')[-1].lower() return … -
Why is my Django serializer returning only Match data and not including related Score data in the API response?
I'm working with Django REST Framework and trying to create an API endpoint that returns live match details along with their associated scores. I have two models, Match and Score, where Score has is associated with Match with a foreignkey. However, when I serialize the Match model, the response only includes match details and does not include any score information. Here’s what my serializers look like: class ScoreSerializer(serializers.ModelSerializer): class Meta: model = Score fields = ['id', 'run', 'wickets', 'overs'] class MatchSerializer(serializers.ModelSerializer): scores = ScoreSerializer(many=True, read_only=True) class Meta: model = Match fields = '__all__' Here is my view code: def livematch(request): live_matches = Match.objects.filter(match_mode='Live') serializer = MatchSerializer(live_matches, many=True) return Response({'success': True, 'data': serializer.data}) -
How to structure a Django DRF project for handling multiple tests and responses
I am working on a Django project using Django REST Framework (DRF), where I need to define a list of tests. Each test consists of multiple questions, and there are corresponding answers for those questions. My initial idea is to create an app called tests and use two CSV files: One CSV file containing all the questions for different tests. Another CSV file containing all the answers. However, I am concerned that this approach might make the code confusing and difficult to maintain. Questions: What is the best architecture for implementing this feature in Django DRF? Is storing test questions and answers in CSV files a good approach, or should I use models and a database instead? If there are any existing similar open-source projects on GitHub, could you provide references? I would appreciate any guidance or best practices on how to structure this project effectively. -
Chaining filter with django filter and django autocomplete light
I am trying to combine Django Filters (DF) with Django Autocomplete Light (DAL). I also want to chain the filter on a few fields in my model. For instance, before applying the DF to my model, I'd like to accomplish the following: Select a certain country. Filter all regions within the selected country. Filter all the cities within the selected region. I have implemented DF and DAL separately and have no issues, which indicates that my views are working as intended. Therefor I don't see any point to share the URLs. I can the see the following response in the console when manually testing DAL in another form: This means that the forwarding in DAL works. However, when I try DF together with DAL: I see that the dictionary values are not set. Which is correct because in the drop-down form I don't see any filtering. I can only auto complete my search for the country field. The region and city fields are not working properly. Views: class CountryAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Country.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs class RegionAutoComplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Region.objects.all() country = self.forwarded.get("country", None) if country: qs = qs.filter(country=country) if self.q: qs … -
Django translation for uz-cyrl return uz instead
I have configured my django LANGUAGES like import os from django.utils.translation import gettext_lazy as \_ from config.settings.base import BASE_DIR LANGUAGE_CODE = "en" USE_I18N = True LANGUAGES = ( ("uz", _("Uzbek")), ("uz-cyrl", _("Cyrillic")), ("ru", _("Russian")), ("en", _("English")), ("ar", _("Arabic")), ) LOCALE_PATHS = [os.path.join(BASE_DIR, "locale")] I have translated texts in all .po files and compiled them. In local runserver it works with Accept-Language: uz-cyrl properly, but through docker-compose it returns uz translation instead, what might be the reason? I have used different base docker images like python3.11-slim, python3.11 itself but not worked.