Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't load my CSS login page in Django admin
I have a Django project that I deployed without really adding any styling for 2 reasons: I didn't know any front-end back then. I wanted to do it for the sake of doing it. Now, I have written HTML and CSS for the login page. The first place I want to apply it is the admin page, but this is what I see (as shown in the picture I shared). I can't find the problem in my project. I also uploaded the project to GitHub here: https://github.com/manirng/sukablyat-django Please ignore the name; I never thought it would go online. @import url('https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;1,300&display=swap'); *{ margin: 0px; padding: 0px; font-family: 'Poppins',sans-serif; } #bg-video{ width: 100%; height: 100vh; position: absolute; object-fit: cover; } section{ display: flex; justify-content: center; align-items: center; min-height: 100vh; width: 100%; background-position: center; background-size: cover; } .box{ position: relative; width: 400px; height: 450px; display: flex; justify-content: center; align-items: center; border: 2px solid white; border-radius: 20px; } h2{ font-size: 2em; color: white; text-align: center; } .input-field{ position: relative; margin: 20px 0; width: 310px; border-bottom: 2px solid white; } .input-field label{ position: absolute; top: 50%; left: 5px; transform: translate(-50); color: white; font-size: 1em; pointer-events: none; transition: .5s; } input:focus ~label, input:valid ~label{ top: -5px; … -
Django: Separate session expiry times for "normal" website and admin area
It would be nice if there were an easy way to define separate session expiry time for the admin area of a django website. So, admin users could log themselves into the "normal" website (seen by all users) but when they try to access the admin area for the first time, they get prompted again to enter their password. They could then do their work in the admin area and continue browsing the website for a few hours, all without entering their password again. The next day, they continue browsing the website, but upon returning to the admin area, need to input their password again. Is there a well-established pattern for this? Or a plugin that implements it? -
unable to make changes on DB or admin after crud operation./formset
I am building a mid-level project called School-Admin Panel with Django. I have completed most of the segments sucessfully, but I am having an issue with the performance forest. The formset loads and displays correctly in the browser, but after I click submit, no changes are made in the DB nothing updates on the admin side. Please help me. I am sharing portions of my code below: forms.py class PerformanceForm(forms.ModelForm): class Meta: model = Performance fields = ["student", "course", "marks", "grade"] widgets = { 'student': forms.HiddenInput(), 'course': forms.HiddenInput(), } PerformanceFormSet = modelformset_factory( Performance, form=PerformanceForm, extra=0, # only existing performances can_delete=False ) views.py def edit_performance(request): queryset = Performance.objects.all() # optionally filter by course if request.method == "POST": formset = PerformanceFormSet(request.POST, queryset=queryset) if formset.is_valid(): formset.save() return redirect("edit_performance") else: # Print errors for debugging print(formset.errors) else: formset = PerformanceFormSet(queryset=queryset) return render(request, "students/performance_edit.html", {"formset": formset}) template (performance_edit.html) <h1>Edit Performance</h1> <form method="POST"> {% csrf_token %} {{ formset.management_form }} <table border="1" cellpadding="5"> <thead> <tr> <th>Student</th> <th>Course</th> <th>Marks</th> <th>Grade</th> </tr> </thead> <tbody> {% for form in formset %} <tr> <!-- Display student/course names --> <td>{{ form.instance.student.name }}</td> <td>{{ form.instance.course.name }}</td> <!-- Editable fields --> <td>{{ form.marks }}</td> <td>{{ form.grade }}</td> <!-- Hidden inputs --> {{ form.student }} … -
Django Strategies for processing large datasets from an external API without a local replica table
I am building an SMS gateway system in Django that acts as an interface between university data sources (e.g., student information systems) and an SMS provider. The Architecture: To ensure data freshness and avoid redundancy, we decided not to maintain a local Recipient table (mirroring the external database). Instead, we use a Stateless/Proxy architecture: User selects filters (e.g., "Faculty: Engineering") in the frontend. Backend fetches the student list in real-time from the external API. We iterate through the results and create a "Snapshot" log (SmsDispatch model) for history/reporting. We send the SMS. The Problem: The external API might return large datasets (e.g., 20,000+ students). I am concerned about: Memory (OOM): Loading 20k objects into a Python list before saving to the DB. Timeouts: The external API being slow, causing the HTTP request or the Celery task to hang. The AI suggested Approach: plan to use Celery with Python Generators and Django's bulk_create to stream data and write in batches. My Question is: Is the chose of not saving the data local a good way? Is this "Generator + Batch Insert" pattern the standard way to handle this in Django/Celery to prevent OOM errors? How should I handle Partial Failures? If … -
inject an image with the other info in the response body in djangorestframework
hy i really need to send an image within the Response object of the djangorestframework endpoint . if there is anyone know how please take a moment and send a comment. Take into consideration not just the image will be sent there is some other info must be sent in the response body -
Displaying related items in an inline formset in Django
I have an inline formset in Django. I have a table called SubItem which is related to Item. Many SubItems to one Item. Some Items don't have any SubItems. Sections of code are obviously missing from below. The issue I am having is the sub items are not being displayed in the template. They don't seem to be bolting on to the main item in the inline formset using the item.subItems code. How do I display related fields like this in an inline formset? I don't need to be able to edit the sub items. view.py accountQuantityForm = AccountQuantityFormSet(instance=account) # Get items linked to an Account instance items = Item.objects.filter(accountquantity__account=account).distinct() for item in items: subItems = SubItem.objects.filter(item=item) # Add the sub items to the item object for display # item.subItems doesn't exist yet, we are creating it and adding the queryset of subItems to it. item.subItems = subItems # apply the filtered items queryset for display in accountQuantityForm for form in accountQuantityForm.forms: form.fields['item'].queryset = items context = { 'accountQuantityForm':accountQuantityForm, } template.html {% for form in accountQuantityForm %} Display form items here {% if form.instance.item.subItems.exists %} {{form.instance.item.subItems}} This is where I would insert the sub items below the main item in … -
How do I make reusable HTML elements in a Django project?
I'm new to Django, and I'm working on a project where I'm reusing static pages and changing them to be suitable Django templates. As a part of the previous project, I made some custom HTML elements using JavaScript files and customElements.define() since I'm not familiar with React. I realized that Django's templates can't modify the static JS files where these elements live, and in particular links can't be modified. The main element that I really want to be able to port over to this project is a navigation bar at the top of the screen that has a link to the homepage, and, depending on whether the user is logged in or not, will either show "login" + "register" buttons, or a notification icon and profile picture. I don't really know what the best way to do this is, I've seen some suggestions where I turn the navbar element into a templatetag, and some others are just placing the raw HTML into a file and including that inside the templates. This is the current code that I have for my navbar: /** * The main navigation bar that should only present one time in each page * of the website. … -
i need help get expirience [closed]
I learned python, django, computer science etc. to create web-sites. My level is really not good yet. I can barely create web-sites with gemini's help. Could anyone give me tips on how to get jobs, even low paid, to get some more expirience? I would prefer remote jobs. Possibly starting from a low level and gradually getting more difficult with repeated tasks. here is my github. and project link. github: https://github.com/daniel4191 project: 15.165.239.111 Thank you for watched my post. I really want better then past and want to really good expert -
Django channels tutorial issue
As I am following the Django channels tutorial (here is the link: https://channels.readthedocs.io/en/latest/tutorial/part_2.html ), I won't post any code except the specific problem I am having. In my code for the chat/routing.py, I have: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()), ] which seems to be identical to that which is given in the tutorial. Trying both single and double quotes, I get the error: SyntaxWarning: invalid escape sequence '\w' r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi() Everything I can find says one is supposed to pre-pend the r to make the expression a regular expression, but clearly I have done so to no effect. What am I doing wrong? Have I missed something? I have copied the line from the tutorial and compared it to mine and it is identical. Thanks in advance. -
ajax request in django
I implemented the post like feature using ajax in the Django project, but it doesn't work. And it gives a 404 error in the console. template.html <script> $(document).ready(function(){ $(".line-button").click(function(){ var post_id = $(this).closest("post").data("post-id"); var button = $(button); $.ajax({ type: 'POST', url: 'like-post/', data: {'post_id': post_id, 'csrfmiddlewaretoken':'{{csrf_token}}'}, success: function(data){ if(data.liked){ button.text('unLike'); }else{ button.text('Like'); } $(".likes-count").text(data.post_likes_count); } }) }) }) </script> views.py @require_POST def like_post(request): post_id = request.POST.get("post_id") post = get_object_or_404(Post, id=post_id) if request.user in post.likes.all(): post.likes.remove(request.user) liked = False else: post.likes.add(request.user) liked = True post_likes_count = post.likes.count() response_data = { 'liked': liked, 'post_likes_count': post_likes_count } return JsonResponse(response_data) urls.py path('like-post/', views.like_post, name="like_post"), -
Python Django Rest Framework
what is the difference between decorator @api_view and @csrf_exempt in project level django rest framework? I need the difference and which is better to develop the project. -
Django Summernote: How to delete attachment files from server when removing them from admin?
When I delete a file from the Attachment model (which is provided by django-summernote), the record is removed from the database, but the actual file remains on the server. I want to make sure that whenever an attachment is deleted, its file is also removed from the filesystem. -
MySQL DB Optimization
I am working on a table where compared data of colleges have been stored. But facing difficulty to query data in low response time. I am creating an API to get some analytics data within 300ms but a simple query on this table takes more than 1-2 sec. I am thinking of re-design the table or create another table in different format. Tried multiple ways but couldn't find the right solution. Tech stack - MySql, Django, DRF Table name - compared_college. Columns - id, college_1, course_1, college_2, course_2, college_3, course_3, college_4, course_4 So basically each college has a course which are compared. Max 4 college-course combination can be compared at once and there entry goes into this table. Each course is mapped to a college and a domain and level. But a college can b mapped to multiple course. Master Tables and column- College - id, name, published Course - id, name, published, domain, level Now compared_collge has more than 40lakh rows. I want some analytics data - Top 10 most compared colleges based on domain or level or without domain-level filter. Top 10 most compared combination of college (pair) based on domain or level or without filter. Top 10 … -
Tailwind CSS is overriding static css in Django
The problem I am having is whenever I try to use tailwind and css (as static), the tailwind overrides the static css file. I tried moving tailwind invokation tags after, before static css invokation, but it didn't work. Whenever I remove tailwind from my template, the static css starts working. How can I use both ? I need to use css file to change properties in django forms. HTML- {% load tailwind_tags %} {% tailwind_css %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{% block title %} {% endblock %}</title> {% load static %} <link rel="stylesheet" href="{% static 'base.css' %}"> </head> <body> <div class="bodydiv"> {% block body %} {% endblock %} </div> </body> </html> CSS- body{ background-color: aqua; } settings.py- """ Django settings for tweeterproject project. Generated by 'django-admin startproject' using Django 5.1.2. For more information on this file, see https://docs.djangoproject.com/en/5.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-9piqti35i-q&85=cebmg*td+g=ut#f$k+t0cttav^_sb8izu-)' … -
Django + allauth email first authentication
I have a django rest api app where I want to setup a custom authentication flow. Here is how I want it to work. Sign Up User enters email User gets email verification code User enters verification code User adds a password User selects a username and a display name User selects a plan User enters billing information (may not be necessary if they choose a free plan) User is now fully logged in! Login User enters email (if account doesnt exist or is not past step 4 of signup transfers to step 2 of signup) User enters password (only works if past step 4) User is routed to step 5-8 of signup if they are not completed User logs in Social Signup I want this to essentially bypass signup steps 1-4 and link a social account. It seems allauth requires you to signup with a password, and I cannot figure out how to get this flow to work. I am also wondering the correct way to implement this. I was thinking about using another module thats not allauth, however most other modules do not have support for other social apps. How should I go about implementing this? -
How do I use Django for another project?
I am trying to start a project using Django. I used Django once, and now I would like to use it again, but this time in a different folder. I keep getting stuck in the terminal trying to execute the commands to install Django. This is what I keep on seeing. $ pip install pipenv Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: pipenv in c:\users\shawonne shann\appdata\roaming\python\python313\site-packages (2025.0.3) Requirement already satisfied: certifi in c:\users\shawonne shann\appdata\roaming\python\python313\site-packages (from pipenv) (2025.6.15) Requirement already satisfied: packaging>=22 in c:\users\shawonne shann\appdata\roaming\python\python313\site-packages (from pipenv) (25.0) Requirement already satisfied: setuptools>=67 in c:\users\shawonne shann\appdata\roaming\python\python313\site-packages (from pipenv) (80.9.0) Requirement already satisfied: virtualenv>=20.24.2 in c:\users\shawonne shann\appdata\roaming\python\python313\site-packages (from pipenv) (20.31.2) Requirement already satisfied: distlib<1,>=0.3.7 in c:\users\shawonne shann\appdata\roaming\python\python313\site-packages (from virtualenv>=20.24.2->pipenv) (0.3.9) Requirement already satisfied: filelock<4,>=3.12.2 in c:\users\shawonne shann\appdata\roaming\python\python313\site-packages (from virtualenv>=20.24.2->pipenv) (3.18.0) Requirement already satisfied: platformdirs<5,>=3.9.1 in c:\users\shawonne shann\appdata\roaming\python\python313\site-packages (from virtualenv>=20.24.2->pipenv) (4.3.8) Shawonne Shann@Latitude-E5450 MINGW64 /c/codingprojects/selfpace/selfpacefolder $ pipenv install django bash: pipenv: command not found What should I do -
How to persist multi-step form data between views in Django without committing to DB?
One-line project/context. Short description of the problem and constraints. Minimal code: models, the two views, form classes, snippets of urls.py. Exact observed behavior or error. Alternatives tried (session, temp model) and why they’re insufficient. Ask: “Given X and Y, which approach best ensures Z, and how to implement it? -
iOS/web Auth Client ID Handling for Google Sign In
To preface, I'm not asking for a direct fix here, I'm just curious if what I'm doing is the appropriate auth flow for setting dynamic client ID based on device platform. I am 2 applications that use the same Django Allauth backend. One of them is for web, and the other is in Flutter (iOS). Both applications would call an endpoint that routes to GoogleDirectLogin(APIView) note that the implementation I currently have a method get_client_id that dynamically use the appropriate client ID based on device type (X-Client-Type) class GoogleDirectLogin(APIView): permission_classes = [AllowAny] def post(self, request): # Get token from request token = request.data.get('id_token') or request.data.get('access_token') if not token: return Response( {'error': 'Missing token in request'}, status=status.HTTP_400_BAD_REQUEST ) # importing middleware is crucial for checking multiple client ID based on JSON Header value from auth_backend.middleware import get_client_id # Import from middleware client_id = get_client_id(request) print(f"using client ID: {client_id}") try: # Verify Google token identity_data = id_token.verify_oauth2_token( token, google_requests.Request(), client_id, clock_skew_in_seconds=10 ) # Validate issuer if identity_data.get('iss') not in ['accounts.google.com', 'https://accounts.google.com']: return Response( {'error': 'Invalid token issuer'}, status=status.HTTP_400_BAD_REQUEST ) # # Exchange token with your internal API response = requests.post( settings.INTERNAL_API_CALL_GOOGLE, json={'access_token': token} ) response.raise_for_status() auth_data = response.json() return Response({ 'access': auth_data['access'], … -
Flaky Circle CI tests (django): ImportError: cannot import name "task" from "app.tasks" (unknown location)
Sometimes, I have many flaky test failures due to one error: ImportError: cannot import name 'task_import_events_to_db' from 'app.tasks' (unknown location) It seems the tests fail because of this import error. Meanwhile, other branches pass without issues, and tests also pass normally after merging. App is in INSTALLED APPS, locally everything works. But not on circle ci Stack: Django, PostgreSQL, Redis -
KeyError 'email' for django-authtools UserCreationForm
I am experiencing an error for which I can’t find an origin. I believe the error stems from GitHub - fusionbox/django-authtools: A custom User model for everybody!, and disclaimer, I have asked this same question on the project’s GitHub repository over a year ago, but nobody has answered, hopefully someone may have some insights here. Every now and then Django complains that email is not in self.fields[User.USERNAME_FIELD], when I try to open the admin 'Add user' form, see below I can see that email isn’t in self.fields but why it isn’t is not clear to me. What absolutely confuses me is that the error is sporadic: If I experience the error in my main browser window, I don’t in a new Incognito window Restarting the app makes the error go away, for some time, but then it reappears, and the only way to solve it is to restart the app. My UserCreationForm, a child of authtools’s UserCreationForm, looks like this class UserCreationForm(UserCreationForm): """ A UserCreationForm with optional password inputs. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["password1"].required = False self.fields["password2"].required = False # If one field gets autocompleted but not the other, our 'neither # password or both password' validation … -
Django check at runtime if code is executed under "runserver command" or not
I've a project based on django that wrap some custom code, this code during import load some heavy file before to be executed. I need to check if imports are executed under "runserver command" or not, in this way I can prevent loading heavy files during django installation. How can i check if code is executed under runserver command -
Django REST project doesn’t detect apps inside the “apps” directory when running makemigrations
I have a Django REST project where I created a directory called apps to store all my apps. Each app is added to the INSTALLED_APPS list in my settings file like this: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # APPS 'apps.accounts.apps.AccountsConfig', 'apps.ads.apps.AdsConfig', ] But when I run python manage.py makemigrations, Django doesn’t detect any changes — it seems like it doesn’t recognize my apps at all. Can anyone help me figure out what might be wrong? Thanks a lot -
Cannot query "admin": Must be "ChatMessage" instance in Django
In View Function it can show this error Request Method:GETRequest URL:http://127.0.0.1:8000/inbox/Django Version:4.2.25Exception Type:ValueErrorException Value:Cannot query "admin": Must be "ChatMessage" instance.Exception Location:D:\Socialmedia\.venv\lib\site-packages\django\db\models\sql\query.py, line 1253, in check_query_object_typeRaised during:core.views.messages.inboxPython Executable:D:\Socialmedia\.venv\Scripts\python.exePython Version:3.9.13Python Path:['D:\\Socialmedia', 'C:\\Users\\ER-RPJ\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\ER-RPJ\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\ER-RPJ\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\ER-RPJ\\AppData\\Local\\Programs\\Python\\Python39', 'D:\\Socialmedia\\.venv', 'D:\\Socialmedia\\.venv\\lib\\site-packages'] def inbox(request): if request.user.is_authenticated: user_id = request.user chat_messages = ChatMessage.objects.filter( id__in=Subquery( User.objects.filter( Q(chat_sender__chat_receiver=user_id) | Q(chat_receiver__chat_sender=user_id) ).distinct().annotate( last_msg=Subquery( ChatMessage.objects.filter( Q(sender=OuterRef('id'), receiver=user_id) | Q(receiver=OuterRef('id'), sender=user_id) ).order_by('-id')[:1].values_list('id', flat=True) ) ).values_list('last_msg', flat=True).order_by('-id') ) ).order_by('-id') context = { 'chat_messages': chat_messages, } return render(request, 'chat/inbox.html', context) In My model class ChatMessage(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='chat_user') chat_sender = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='chat_sender') chat_receiver = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='chat_receiver') message = models.TextField() is_read = models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) mid=ShortUUIDField(length=7,max_length=25,alphabet='abcdefghijklmnopqrstuvwxyz') # def __str__(self): # return self.user class Meta: verbose_name_plural = 'Chat messages' -
Is it reasonable to use Cloud storage for async webhook processing on Cloud Run
I'm processing webhooks on Cloud Run (Django) that need async handling because processing takes 30+ seconds but the webhook provider times out at 30s. Since Cloud Run is stateless and spins up per-request (no persistent background workers like Celery), I'm using this pattern: # 1. Webhook endpoint def receive_webhook(request): blob_name = f"webhooks/{uuid.uuid4()}.json" bucket.blob(blob_name).upload_from_string(json.dumps(request.data)) webhook = WebhookPayload.objects.create(gcs_path=blob_name) create_cloud_task(payload_id=webhook.id) return Response(status=200) # Fast response And then our cloud task calls the following endpoint with the unique path to the cloud storage url passed from the original webhook endpoint: def process_webhook(request): webhook = WebhookPayload.objects.get(id=request.data['payload_id']) payload = json.loads(bucket.blob(webhook.gcs_path).download_as_text()) process_data(payload) # 30+ seconds bucket.blob(webhook.gcs_path).delete() My main query points: Is GCS + Cloud Tasks the right pattern for Cloud Run's model, or is storing JSON directly temporarily in a django model a better approach since Cloud Tasks handles the queueing? Should I be using Pub/Sub instead? My understanding is that pubsub would be more appropriate for broadcasting to numerous subscribers, currently I only have the one django monolith. Thanks for any advice that comes my way. -
Django ORM: Add integer days to a DateField to annotate next_service and filter it (PostgreSQL)
I am trying to annotate a queryset with next_service = last_service + verification_periodicity_in_days and then filter by that date. I am on Django 5.2.6 with PostgreSQL. last_service is a DateField. verification_periodicity lives on a related SubCategory and is the number of days (integer). Models (minimal): # main/models.py class Category(models.Model): name = models.CharField(max_length=100) class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='subcategories') name = models.CharField(max_length=100) verification_periodicity = models.IntegerField() # days class Asset(models.Model): sub_category = models.ForeignKey(SubCategory, on_delete=models.PROTECT) last_service = models.DateField(null=True, blank=True) Goal: Compute next_service = last_service + verification_periodicity days in the database, expose it in the API, and support filtering like ?next_date__gte=2025-12-06. What I tried: Simple cast and multiply: from django.db.models import ExpressionWrapper, F, DateField, IntegerField from django.db.models.functions import Cast qs = qs.annotate( next_service = ExpressionWrapper( F('last_service') + Cast(F('sub_category__verification_periodicity'), IntegerField()) * 1, output_field=DateField() ) ) This does not shift by days and later caused type issues. Filtering by the annotated date also did not work as expected. Using a Python timedelta: from datetime import timedelta qs = qs.annotate( next_service = F('last_service') + timedelta(days=1) * F('sub_category__verification_periodicity') ) This produced a duration in seconds in the serialized output. Example: "next_service": "86400.0" for one day, rather than a proper date. I need a date. Errors seen along …