Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it correct to modify `django.db.connections.databases` dynamically to multiple databases? Or is it better to deploy a separate API per client?
This is my first time developing a multi-tenant SaaS application in Django, in this SaaS each company has its own PostgreSQL database, and these databases are created dynamically when a company registers. I cannot predefine all databases in settings.DATABASES, as companies can register at any time without requiring a server restart. My current solution uses Middleware to detect the company from the subdomain or a JWT token and then modify connections.databases at runtime to configure the connection to the company's database: import redis from django.db import connections from django.core.exceptions import ImproperlyConfigured from django.utils.connection import ConnectionDoesNotExist from rest_framework_simplejwt.authentication import JWTAuthentication from myapp.models import Company # Company model stored in the global database class CompanyDBMiddleware: def __init__(self, get_response): self.get_response = get_response self.jwt_authenticator = JWTAuthentication() self.cache = redis.Redis(host='localhost', port=6379, db=0) def __call__(self, request): company_db = self.get_database_for_company(request) if not company_db: raise ImproperlyConfigured("Could not determine the company's database.") # Register connection only if it does not exist in `connections.databases` if company_db not in connections.databases: connections.databases[company_db] = { 'ENGINE': 'django.db.backends.postgresql', 'NAME': company_db, 'USER': 'postgres', 'PASSWORD': 'your_password', 'HOST': 'localhost', 'PORT': '5432', 'CONN_MAX_AGE': 60, # To avoid opening and closing connections on each request } request.company_db = company_db response = self.get_response(request) # Close connection after the response try: … -
handle auth workflow with django API and react
I have a frontend app written in react I have a backend application which is a django server. On top of that I am working with a 3rd party True Layer (Open Banking API) The first thing I want to implement is the authentication which I did correctly. However, I am trying to write a method to refresh my access_token thanks to the refresh_token given by the TrueLayer API when user first authenticate. The problem is that from what I read online the good practice is to have the refresh_token stored into the HTTP only cookies. So I did something like this def truelayer_callback(request): code = request.GET.get('code') token_data = { "grant_type": "authorization_code", "client_id": settings.TRUELAYER_CLIENT_ID, "client_secret": settings.TRUELAYER_CLIENT_SECRET, "redirect_uri": REDIRECT_URI, "code": code, } try: data = requests.post(TOKEN_URL, data=token_data).json() access_token = data.get('access_token') refresh_token = data.get('refresh_token') if access_token: query_params = urlencode({'token' : access_token}) response = HttpResponseRedirect(f'{FRONTEND_URL}?{query_params}') response.set_cookie(key='refresh_token', value=refresh_token, httponly=True, secure=False, samesite='Lax') return response return HttpResponseRedirect(f'{FRONTEND_URL}?error=No access token received') except Exception as e: return HttpResponseRedirect(f'{FRONTEND_URL}?error={str(e)}') I set the cookie refresh_token in the response. But in my next method, which is the method called to refresh the access_token when I try to access my refresh_token from cookies I get None: def check_refresh_cookie(request): refresh_token = request.COOKIES.get("refresh_token") # … -
Does Django automatically recognize registration/login.html as the login template?
Does Django automatically recognize registration/login.html as the login template? I'm working on a Django project and want to use Django's built-in authentication system for user login. If I don't set in url in urls.py My question is: Does Django automatically recognize registration/login.html as the default login template? If so, how does Django determine this file's location? Do I need to set anything in settings.py to make this work? Where is written the logic for this built in login -
Django WSGI and ASGI
This is my project structure. . ├── chat # <== my app name │ ├── apps.py │ ├── consumers.py │ ├── __init__.py │ ├── migrations │ │ ├── __init__.py │ ├── models.py │ ├── routing.py │ ├── templates │ │ └── chat │ │ ├── index.html │ │ └── room.html │ ├── urls.py │ └── views.py ├── config # <== project configuration │ ├── asgi.py │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── manage.py setting.py file ALLOWED_HOSTS = ["*"] INSTALLED_APPS = [ "daphne", ..., ..., "chat", ] # for HTTP protocal WSGI_APPLICATION = "config.wsgi.application" # for Websocket protocal ASGI_APPLICATION = "config.asgi.application" chat/urls.py file from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), ] wsgi.py file from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") application = get_wsgi_application() chat/routing.py file from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi()), ] asgi.py file from chat.routing import websocket_urlpatterns os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") application = ProtocolTypeRouter( { "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(websocket_urlpatterns)), ), } ) After setting up all the configurations, I ran the HTTP and WebSocket servers on separate ports: Run the HTTP server (with Gunicorn): gunicorn config.wsgi:application --bind 0.0.0.0:8000 Run the WebSocket server (with Daphne): … -
Split data of an Ajax call to multiple div in Django
I have this ajax call $.ajaxSetup({ data: {txtSearch: $('#txtSearch').val(), prefilter: $('#prefilter').val(),csrfmiddlewaretoken: '{{ csrf_token }}' },}); $.ajax({ type: "POST", url: "article-filter2/", success: function (data) { $("#div_tab_search_results_contact").html(data.html_table); // working $("#div_tab_search_results_company").html(data.html_table); // not working if I call it a second time } }); data.html_table contains 2 tables and I would like to put the first one in $("#div_tab_search_results_contact") and the second one in $("#div_tab_search_results_company") based on the id's of the tables. I tried to search but what I found was in PhP Not able to split the Ajax response in separate Div Here is the end of my view.py article-filter2/ : def article_filter2(request): data = dict() [...] data['html_table'] = render_to_string('grid.html', {'available_lessons': available_lessons, 'available_lessons_company': available_lessons_company },request=request) return JsonResponse(data) Thanks to anybody that can help me -
My Django Project is sending the same email from different apps
I have a Django Project with two different apps: contact_us and booking. both are forms on different sections of the site. when the form for booking request is being sent it saves the info to the table and it is sending a confirmation email... the problem is that the content of the email is from the contact_us view... it is sending from the same email account but the content should be different. From Contact i get the email with Contact info, i added logs everywhere to see where the error is but is not giving me any clues except that contact_us might be overwriting booking at some point my settings are like this: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'host' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'email@email.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER public_pages views.py def contact_us(request): logger.debug("Request method: %s", request.method) if request.method == 'POST': logger.debug("Form data received: %s", request.POST) form = ContactForm(request.POST) if form.is_valid(): logger.debug("Form is valid") contact = form.save() # Save the form data to the ContactUs model logger.debug("Contact saved: %s", contact) try: # Send email to the user send_mail( 'We Received Your Message', f'Thank you for contacting us, {contact.name}. We will review your message shortly.', settings.DEFAULT_FROM_EMAIL, … -
Django Cloud Storage NoSuchKey
I deploy a Django/React project with GKE, Cloud SQL as DB, Cloud Storage for static file. When I trying upload files(both by Django admin and API), the url I get always tells me This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>NoSuchKey</Code> <Message>The specified key does not exist.</Message> <Details>No such object: my-bucket/media/uploads/01.JPG</Details> </Error> I tryed directly upload file in GCP console and file can be visited. Also when I use gsutil cp .gitignore gs://my-bucket/media/ file can be visited. below are my settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.1/howto/static-files/ DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' STATICFILES_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'my-bucket' GS_MEDIA_BUCKET_NAME = 'my-bucket' GS_DEFAULT_ACL = 'publicRead' GS_FILE_OVERWRITE = False # STATIC_ROOT = '/app/static' STATIC_URL = f"https://storage.googleapis.com/{GS_BUCKET_NAME}/static/" MEDIA_URL = f"https://storage.googleapis.com/{GS_MEDIA_BUCKET_NAME}/media/" and deployment.yaml apiVersion: apps/v1 kind: Deployment metadata: name: app spec: replicas: 2 selector: matchLabels: app: app template: metadata: labels: app: app spec: serviceAccountName: my-service-account containers: - name: app image: asia-east1-docker.pkg.dev/my-project-id/app/backend:latest ports: - containerPort: 8000 env: - name: DB_USER - name: DB_PASSWORD - name: DB_NAME - name: DB_HOST - name: DB_PORT resources: requests: memory: "512Mi" cpu: "500m" limits: memory: "1Gi" cpu: "1" - name: cloud-sql-proxy image: gcr.io/cloud-sql-connectors/cloud-sql-proxy:latest args: volumeMounts: - … -
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 …