Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
single and double quotes in json.parse
How can I pass a list of characters from Django to Javascript? I'm passing a dictionary from Django to Javascript in the render function. In javascript I parse the data as always using the code const dates = JSON.parse("{{dates|safe}}") This works for numbers, but for strings I get some error JSON.parse: unexpected character at line 1 column 2 of the JSON data I could pinpoint the problem down to: const this_works = JSON.parse('["1","2"]') const this_throws = JSON.parse("['1','2']") But I can't use the ' as the outermost character here as the {{}} notation seems to require ". What is the workaround to this problem? -
Django's Password Reset Email is not rendering the CSS properly but grabbing the HTML content
I am using Django's password reset and I'm trying to send the password reset with a custom HTML template for when the user receives the email, its nicely formatted. Right now when I send it, it's sending the content of what's in the HTML file, but the styling isn't there for some reason and I can't figure out why. There should be spacing and all of that, so it looks nice, but it isn't doing it. password_reset_email.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Reset Your Password</title> <style> /* Inline styles for email clients */ body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; background-color: #f5f5f5; margin: 0; padding: 0; } .password_reset_email { max-width: 600px; margin: 0 auto; padding: 2rem; background: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); } .password_reset_email-header { text-align: center; margin-bottom: 2rem; } .password_reset_email-header h1 { color: #2c3e50; font-size: 2rem; margin-bottom: 1rem; } .password_reset_email-content { margin-bottom: 2rem; } .password_reset_email-content p { margin-bottom: 1rem; color: #333; } .password_reset_email-button { display: inline-block; background: #3498db; color: white; padding: 0.8rem 1.5rem; border-radius: 4px; text-decoration: none; margin: 1rem 0; } .password_reset_email-footer { margin-top: 2rem; padding-top: 1rem; border-top: 1px solid #ddd; … -
How to add a validation to a model serializer so that it ensures at least one of two fields are passed for sure?
I have made a model in Django which includes two fields, let's call them file and code. file is a file field and code is a character field. I've set them both as blank=True and null=True. Set the validation in model by overriding the clean() method to check if file and code both don't exist, it throws a validation error saying at least one should be passed. Called full_clean() in the overridden save() method. This approach does allow me to add this sort of at least one validation for these two fields on the model level and even through the admin panel. But, in the serializer, or while hitting the API, it doesn't really throw any error if I don't pass both, that's probably coz my model basically says both aren't required individually. What I tried doing is that I have overridden the validate() method in the serializer, it's a model serializer btw. In the overridden validate() method I added the check as: if file not in data and code not in data: raise serializers.ValidationError("At least one of the two must be passed.") What should I do instead? Even a change in the model might help but it should keep … -
I want to pass Hex Colour Code into a CSS inline style on an HTML page
I have a Django project that has a database of colours with their Hex values. I want to display this as a swatch in a table. <tbody> {% for item in items_page %} <tr> <td scope="row">{{ item.manufacturer }}</td> <td scope="row">{{ item.paintname }}</td> <td scope="row">{{ item.hexcode }}</td> <td scope="row">{{ item.type }}</td> <td scope="row">{{ item.colourcategory }}</td> <td scope="row" style='background-color :{{item.hexcode}}'></td> </tr> The issue I have is that this works and displays the swatches but the last line has errors flagged on it. The error red lines are under the <td tag, the word color and the {{item.hexcode}} code. It works but I worry that because of the error it may break further down the line. Is there a correct way of achieving what I am trying to do? Thanks -
Please help me understand why I shouldn't save CSRF tokens in session storage
I am new to webdevelopment and have written some tests in Playwright to test my webapplication. The tests are failing only on Webkit/safari, seemingly due to CSRF validation issues returning 403 Errors on unsafe (POST/PUT/DELETE) requests only. Backend: api.example.com (Django) Frontend: app.example.com (React.js) My current procedure: The user calls a dedicated endpoint api.example.com/api/auth/csrf/ which simply sets the csrf cookie using Set-Cookie default Django behaviour, and returns nothing in the response body. For a subsequent POST Request the csrftoken cookie is read and set as the X-CSRFToken header. The user logs in using a POST request and username password together with this header to get the sessionid in cookies. Subsequent POST requests with csrftoken and session_id in cookies fail, as my React.js application fails to create the X-CSRFToken header (empty header). This only happens for Webkit/Safari, not for Firefox or Chromium. From what I understand, is that even though the Cookies are sent across subdomains, webkit does not allow cookies to be read from document.cookies across different subdomains when setting Samesite=lax, even if the domain is set to .example.com. This is in contrast with chromium and firefox that seemingly do allow this behaviour. In all browsers, I have confirmed that the … -
How can I structure a learning platform with categorized content and searchable tutorials using Django? [closed]
I'm building a web app for educational tutorials. I want to organize content by categories like Python, SQL, and Machine Learning, and allow users to search by topic or keyword. What's a good way to design the models and implement search functionality efficiently in Django? -
How to make the logout dropdown visible in Django-Jazzmin admin panel?
"I just installed Django version 5.2 and replaced the default admin interface with Django Jazzmin version 3.0.1. However, the problem is that the logout dropdown does not appear. I’ve already asked an AI platform and tried all the suggestions provided, but none of them worked." -
Hi there, how can i get the key and values from a dictionary, so i can display each keys with their value on my Django page. I'm new to Django
I want to build a page that has each author with their quote. I have tried, but everything i tried has failed. The function below is what causes me the issues. quotes = { "Arthur Ashe": "Start where you are, Use what you have, Do what you can.", "Steve Jobs": "Don’t watch the clock; do what it does. Keep going.", "Sam Levenson": "Don’t watch the clock; do what it does. Keep going.", " Robert Collier": "Success is the sum of small efforts, repeated day in and day out.", "Nelson Mandela": "It always seems impossible until it’s done.", "Mahatma Gandhi": "The future depends on what you do today.", "Zig Ziglar": "You don’t have to be great to start, but you have to start to be great.", "Dave": "Discipline is doing what needs to be done, even if you don’t want to do it.", "Suzy Kassem": "Doubt kills more dreams than failure ever will.", "Pablo Picasso": "Action is the foundational key to all success." } def mypage(request): messages = [quotes[item] for item in quotes] authors = [item for item in quotes] return render(request, "quotes/mypage.html", {"authors": authors, "quotes":messages}) -
ensure Customuser is being used in Django App
I have a problem with implementing CustomUser in a Django App. My project is called "VendorManagement". My app is "VMP". In settings, I have AUTH_USER_MODEL = 'VMP.CustomUser' set. Here is my CustomUser Model: from django.db import models from django.conf import settings from django.contrib.auth.models import User, AbstractUser from django.utils.timezone import timedelta, now from django.core.exceptions import ValidationError # File validation function def validate_file_type(value): allowed_types = ["application/pdf", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"] if value.content_type not in allowed_types: raise ValidationError("Only PDF and Word documents are allowed.") class CustomUser(AbstractUser): ROLE_CHOICES = [ ('vendor', 'Vendor'), ('customer', 'Customer'), ('admin', 'Admin'), ] role = models.CharField(max_length=20, choices=ROLE_CHOICES, default='customer') groups = models.ManyToManyField("auth.Group", related_name="custom_user_groups", blank=True) user_permissions = models.ManyToManyField("auth.Permission", related_name="custom_user_permissions", blank=True) def is_vendor(self): return self.role == "vendor" def is_customer(self): return self.role == "customer" def is_admin(self): return self. Role == "admin" Here is my views: from django.contrib.auth import get_user_model from .models import * # Get custom User model CustomUser = get_user_model() class RFPViewSet(viewsets.ModelViewSet): serializer_class = RFPSerializer def get_queryset(self): """Vendors see active RFPs, Customers see expired ones""" userid = self.request.user.id # Ensure user is fetched correctly as CustomUser user_instance = CustomUser.objects.filter(id=user.id).first() if user_instance.is_vendor(): return RFP.objects.filter(is_expired=False, is_active=True) elif user_instance.is_customer(): return RFP.objects.filter(customer=user_instance, is_expired=True) return RFP.objects.none() The problme3 i that while the model does include is_customer() and is_vendor(), the functions … -
Cloud SQL Proxy SSL error: `certificate had CN "", expected "<project>:<region>:<instance>"` when connecting to PostgreSQL 14
We're encountering an issue with Cloud SQL Proxy (v1 and v2) when connecting to a newly created PostgreSQL 14 Cloud SQL instance via a Kubernetes deployment on GKE. The error we see in the logs is: certificate had CN "", expected "<project-id>:<region>:<instance-name>" Context: We're using the Cloud SQL Auth Proxy sidecar container in our GKE deployment. The credentials JSON for a service account with the Cloud SQL Client role is correctly mounted and used via -credential_file. The instance connection string is correctly formatted. We’ve verified that the secret mounts and paths are accurate. The same setup works fine for an older PostgreSQL 11 instance. Observations: Proxy starts and listens on 127.0.0.1:5432, but immediately fails on SSL handshake. The error appears to be related to the certificate’s Common Name (CN) being empty or invalid. The username used to connect differs from the old instance (proxyuser) vs. new one (postgres), but it's unclear if that's related. What we've tried: Regenerating and rotating service account keys Verifying IAM permissions Ensuring secrets are properly mounted Running the proxy locally with the same credentials (same error) Question: What could cause the Cloud SQL Auth Proxy to reject the connection due to a CN "" certificate … -
Python/Django: Updated .env Values Not Reflected After Restarting runserver
I'm working with a Django project and using a .env file to manage my environment variables. However, after updating values in the .env file and restarting the server (python manage.py runserver), the new values are not being reflected in the application. Specifically, the SLACK_CLIENT_ID and SLACK_APP_NAME values are not being updated even though I can confirm the .env file is loaded correctly. Here’s what I’ve done: I updated the .env file with the correct values. I restarted the Django development server using python manage.py runserver. I confirmed that the .env file is being loaded (printed debug statements for SLACK_CLIENT_ID and SLACK_APP_NAME). Despite these updates, the app still shows the old environment variable values (e.g., your-slack-client-id). I’ve tried the following: Ensuring that the .env file is in the correct location and formatted properly. Using load_dotenv() to load the .env file in my settings.py. Restarting the server multiple times. Checking the virtual environment. from dotenv import load_dotenv import os load_dotenv() SLACK_CLIENT_ID = os.getenv('SLACK_CLIENT_ID', 'your-slack-client-id') SLACK_APP_NAME = os.getenv('SLACK_APP_NAME', 'Slack Integration') print("SLACK_CLIENT_ID from .env:", SLACK_CLIENT_ID) Even though I’ve removed the fallback value 'your-slack-client-id' and updated the .env file, the print statement still outputs the old value (your-slack-client-id). The new value isn't being picked up. … -
Sudden URLError
I have a crm app that has been working fine until today. There are two registration options, one where I can manually add a user, the second - a user sets up their own account. Both options were working well until today (the first option is still working) but When users complete the sign up page they get the following error (code is at the very bottom): URLError at /register/150 <urlopen error [Errno -3] Temporary failure in name resolution> Request Method: POST Request URL: http://INSERT URL/register/150 Django Version: 3.2 Exception Type: URLError Exception Value: <urlopen error [Errno -3] Temporary failure in name resolution> Exception Location: /usr/lib/python3.8/urllib/request.py, line 1357, in do_open Python Executable: /home/django/regenv/bin/python Python Version: 3.8.10 Python Path: ['/home/django/registrations', '/home/django/regenv/bin', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/django/regenv/lib/python3.8/site-packages'] Server time: Wed, 30 Apr 2025 21:05:48 +0000 Traceback Switch to copy-and-paste view /usr/lib/python3.8/urllib/request.py, line 1354, in do_open h.request(req.get_method(), req.selector, req.data, headers, … ▶ Local vars /usr/lib/python3.8/http/client.py, line 1256, in request self._send_request(method, url, body, headers, encode_chunked) … ▶ Local vars /usr/lib/python3.8/http/client.py, line 1302, in _send_request self.endheaders(body, encode_chunked=encode_chunked) … ▶ Local vars /usr/lib/python3.8/http/client.py, line 1251, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) … ▶ Local vars /usr/lib/python3.8/http/client.py, line 1011, in _send_output self.send(msg) … ▶ Local vars /usr/lib/python3.8/http/client.py, line 951, in … -
Google OAuth Refresh Token Causes Infinite Redirect Loop After Logout and Re-Login in Django App
I’m implementing Google OAuth2 login in a Django-based application. The initial login works fine — I receive both an access token and a refresh token from Google. I only save the refresh token, since the access token expires in one hour and isn’t usable beyond that. After login, the user can use the app and perform all actions. Upon logout, I clear the session and remove stored credentials. However, when the user tries to log in again, the app gets stuck in an infinite redirect loop — Google redirects back immediately to my app (since consent was already granted), and my app fails to authenticate the user because the refresh token exchange fails, so it starts the login process again. This cycle repeats endlessly. Even though I save the refresh token from the first login and attempt to reuse it, this still doesn’t fix the issue. I suspect the refresh token gets invalidated silently (possibly by re-login, password change, or Google’s internal rotation policy). Additionally, this breaks background scheduled tasks (like Gmail API-based scheduled emails), because they depend on the saved refresh token to generate access tokens — which fails if the token becomes invalid. Authorization authorization_url, state = flow.authorization_url( … -
How to Log Old and New Data on Model Updates in Django Rest Framework Using Celery for Asynchronous Processing?
I need to log both the old and new values of fields whenever a model is updated in Django Rest Framework (DRF). The logs should be saved in a separate database or an external system like Elasticsearch. The challenge is to capture both values without querying the database again and without affecting performance. I want to handle this logging process asynchronously using Celery. What I Tried: Used pre_save and post_save signals to detect updates. Tried querying the database to get the old data, but I want to avoid this extra query. Integrated Celery to handle the logging asynchronously, but not sure about the best way to capture the old and new values efficiently. What I Need Help With: How can I capture both old and new data without querying the database? How can I use Celery to handle logging asynchronously to avoid performance issues? Is there an existing pattern or best practice for logging changes in Django models? -
QuerySet returns empty in django
I am trying to get the book list with 3 conditions: Accession number (character varying,10) Physical location (character varying,20) Book status Based on the user input: Accession number should be present in the list provided by the user Physical location should be exact match Book status should be 'Published' qobjects = Q() variable_column = "accession_number" search_type = 'in' filter_string = variable_column + '__' + search_type #Passed accessionNumber as '123','234',456' #Also tried 123,456,567 #Both did not work search_string = '['+accessionNumber+']' qcolumn = Q(**{filter_string: search_string}) qobjects.add(qcolumn, Q.AND) print('print qobjects after adding accession numbers') print(qobjects) location_column="physical_book_location" search_type='iexact' filter_string = location_column + '__' + search_type qcolumn_location = Q(**{filter_string: location}) print('print qobjects after adding location') print(qobjects) qobjects.add(qcolumn_location,Q.AND) qcolumn_status = Q(**{'booK_status': 'PUBLISHED'}) qobjects.add(qcolumn_status, Q.AND) print('print qobjects after adding status') print(qobjects) res_set = Book.objects.filter(qobjects).order_by(location_column). \ values('id', 'title', 'cover_image_name','booK_status', 'accession_number', 'total_image_count',) print('print result set') print(res_set) -
Third Party API Integration with Django (JWT) + Next.js (Redux, RTK Query)
I am creating a NYT News App using Django JWT authentication for registration and login and NextJS, Redux and RTK Query on the frontend. My full stack login/registration system works perfectly and now I want to load the news after logging in. Lets call NYT API json from the backend as raw data. On the frontend I wanna filter out raw news by selecting categories:{} and create a popup in the frontend for the first time users. (These preferences are then stored in DigitalOcean bucket using DigitalOcean functions). I am not sure how to start new api call in the first place and which tools to use. Any help would be appreciated! -
Setting permissions between edit and view only in wagtail
In my Wagtail project, I have a class that inherits from EditView(modelAdmin). Within this class, I override the get_edit_handler method to dynamically set fields as read-only based on user permissions. However, I'm encountering an issue with RichTextField fields: the permission settings only take effect after restarting the application. For example, if I set an InlinePanel to read-only, all InlinePanel instances that include RichTextField fields across the model also become read-only, regardless of their individual permission settings. class JournalEditView(EditView): def form_valid(self, form): self.object = form.save_all(self.request.user) return HttpResponseRedirect(self.get_success_url()) def get_edit_handler(self): """ Overrides the get_edit_handler method from EditView. It checks whether the user has permission to edit each field. If not, the fields for which the user lacks the journal.can_edit_{field_name} permission in their user_permissions will be set as read-only. This applies to FieldPanel, AutocompletePanel, and InlinePanel. """ edit_handler = super().get_edit_handler() user_permissions = self.request.user.get_all_permissions() if not self.request.user.is_superuser: for object_list in edit_handler.children: for field in object_list.children: if isinstance(field, FieldPanel) and f"journal.can_edit_{field.field_name}" not in user_permissions: field.read_only = True elif isinstance(field, InlinePanel) and f"journal.can_edit_{field.relation_name}" not in user_permissions: field.classname += ' read-only-inline-panel' for inline_field in field.panel_definitions: inline_field.read_only = True return edit_handler class JournalAdmin(ModelAdmin): model = models.Journal inspect_view_enabled = True menu_label = _("Journals") create_view_class = JournalCreateView edit_view_class = JournalEditView -
Django CKEditor5 images not displaying on server
I am using Django 5.0 and django-ckeditor-5 to handle rich text stuff in my admin panel, including image uploading by staff. On my local machine (Win11), everything works fine. I can upload the image and it shows correctly in the admin view and in the site view. However, when putting it on my test server (Windows Server 2022, using IIS), when I upload an image, it flashes and then displays the default broken image. Attempting to navigate to the image directly gives a 404, but when I look at the URL of the image and physically find it on the server, its there and I can open it in paint. So the images are uploading into the correct place, the URL of the image in CK editor is showing the correct image, but the image does not want to load. Here is my path settings for the urls.py at the root and the media folder in settings.py urls.py ... urlpatterns += [ path("ckeditor5/", include('django_ckeditor_5.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py ... STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') The setup is identical for both local and on the server in terms of folder structure, the media folder is … -
How to set up docker compose with django and pdm
I have a django project with pdm and docker compose and I set up the codebase volume to enable django hot reload and debugging in the container. Building with the compose config works fine but when I try to run the server with docker compose up -d I hit a python error as if the libs were not picked up properly. The project has the following architecture project/ ├── config/ │ ├── settings.py │ └── urls.py │ └── ... ├── some_django_app/ │ └── ... ├── compose.yaml ├── Dockerfile ├── README.md ├── pyproject.toml └── pdm.lock the compose file is as follows services: web: build: dockerfile: Dockerfile command: pdm run python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 volumes: - .:/app env_file: - .env my dockerfile is as follows # Use an official Python runtime as a parent image FROM python:3.13.2-slim-bullseye # Set environment variables ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 # Set the working directory in the container WORKDIR /app # Install system dependencies RUN apt-get update && apt-get install -y \ build-essential \ libpq-dev \ && rm -rf /var/lib/apt/lists/* # Install PDM RUN pip install --no-cache-dir pdm # Copy the project files into the container COPY . /app # Accept build argument for … -
Django: Saving automated JSON POST from software (no user form!) in several tables (models)
Needed to save POST data in several tables\models in 2 apps (one - only 4 POST receiving) , depending on POST content. One model - ActionFeed will be JSON field and save all input, others - conditionally, looking on various JSON POST values Input data is looking like { "timestamp":"2025-04-29T07:15:12Z", "event":"MissionAccepted", ... } #schematically json_data = json.loads(post_input) Save2ActionFeed (post_inpt) if event=="MissionAccepted" #get neeses fields from json data save2Missionsions (field1, ... , field N) if event=="FSDJump" #get neeses fields from json data save2Location(field1, ... , field M) etc. Needed a sample of save2... methods, please, remember, than no forms, UI, etc - only clean POST -
Django [Postgreq] restore single field/column
I have a model with field creation_date = models.DateTimeField(auto_now_add=True). Doing some complex manipulations with migration file (converting model to multi-table inheritance and creating new objects) I've accidentally overwriten the field above. I have backups but need to overwrite only the single field creation_date as there are some fields in table are not align with current state. I guess there is a way to dump (id, creation_date) in JSON file and update the corresponding objects with for loop. Is there a way to pull data from gzip backup and save it to .json ? Or some more easier way to go? -
How to to debug DB errors in flaky frontend tests with django, htmx and playwright
I'm running a larger Django app that has a test suite that runs both on Debian Bookworm and Trixie. The tests use the test_server fixture and sqlite. We're currently experimenting with HTMX based views, which we test using playwright. A few weeks ago the test covering our new HTMX view started occasionally failing, but only ever on Trixie. The only relevant packages provided by the Debian Trixie host are sqlite 3.46 and python 3.13. Everything else comes in via pip and pyproject.toml in the same versions as on Bookworm. The test does not fail reliably and when it does fail, it doesn't always fail with the same error. The only commonality is that it always fails while trying to get the current session, in order to authenticate the request user (the tested view has an auth decorator). The error messages include django.contrib.auth.models.User.MultipleObjectsReturned: get() returned more than one User -- it returned 2! django/db/models/sql/compiler.py stepping out with List index out of range when trying to load the session cache django.db.utils.InterfaceError: bad parameter or other API misuse when trying to get the session cache. They mostly end up with AttributeError: 'SessionStore' object has no attribute '_session_cache' but there can be different issues … -
Django custom user model stores password in separate table — request.user causes "column users.password does not exist" error
i have created custom user in django class User(AbstractBaseUser, PermissionsMixin): which have password in user_credential table separately . what i want to request.user function i get error like ProgrammingError at /api/planer/user/ column users.password does not exist LINE 1: SELECT "users"."id", "users"."password", Ensured my custom authentication backend returns the correct user Confirmed AUTHENTICATION_BACKENDS is set properly Verified the User model has no password field -
Best way to design database tables for classified ads
I want to post classified ads. So in the context of designing the database is it better to put fields like body_type (which is not going to really change ever) or color into a separate table or keep as part of the overall model? -
Django + DigitalOcean Managed PostgreS: “remaining connection slots are reserved for roles with the SUPERUSER attribute” when using connection pooling
I’m trying to configure Django to use a connection pool against a DigitalOcean Managed PostgreSQL instance, but keep running into this error: OperationalError: connection failed: connection to server at "xxxxxxxxxxxx", port yyyy failed: FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute My DATABASES setting looks like this (Django 5.2+): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': database_name, 'USER': database_user, 'PASSWORD': database_password, 'HOST': database_host, 'PORT': database_port, "OPTIONS": { 'sslmode': sslmode, 'pool': { 'min_size': 5, 'max_size': 150, 'timeout': 20, }, } } } Is this the correct way to enable pooling via Django’s built-in OPTIONS['pool'] settings?