Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
502 Bad Gateway Nginx | Django | Gunicorn on Load Balancer
I have an AWS Elastic Load Balancer (ELB) and listeners which redirect to port 80 internally (certificates and SSL termination at the ELB). I'm running nginx on the EC2 instances, along with php, gunicorn and django/python. The cluster is being set up to host multiple domain names with distinct websites/apps for each. External http/https requests work fine for html and php, returning the pages. For django requests using sockets I'm getting a 502 Bad Gateway error externally, but internally via curl (eg. curl --unix-socket /tmp/gunicorn_.sock http:///app/) it works fine. Externally https:///test (simple Nginx endpoint) works fine None of the logs I can find show errors. eg: [2025-07-31 00:05:07 +0000] [776767] [INFO] Handling signal: term [2025-07-31 00:05:07 +0000] [776771] [INFO] Worker exiting (pid: 776771) [2025-07-31 00:05:07 +0000] [776769] [INFO] Worker exiting (pid: 776769) [2025-07-31 00:05:07 +0000] [776768] [INFO] Worker exiting (pid: 776768) [2025-07-31 00:05:08 +0000] [778670] [INFO] Starting gunicorn 23.0.0 [2025-07-31 00:05:08 +0000] [778670] [INFO] Listening at: unix:/tmp/gunicorn_<domain>.sock (778670) [2025-07-31 00:05:08 +0000] [778670] [INFO] Using worker: sync [2025-07-31 00:05:08 +0000] [778672] [INFO] Booting worker with pid: 778672 [2025-07-31 00:05:08 +0000] [778673] [INFO] Booting worker with pid: 778673 [2025-07-31 00:05:08 +0000] [778674] [INFO] Booting worker with pid: 778674 My server conf server … -
Starting django with python manage.py runserver and getting ModuleNotFoundError: No module named '_msi'
django was working fine my venv got corrupted and I rebuilt it from requirements.txt now getting File "C:\Users\PC\OneDrive\Documents\GitHub\DoseV3Master\venv\Lib\site-packages\msilib_init_.py", line 3, in from _msi import * ModuleNotFoundError: No module named '_msi' went to pypi and got the installer pip install python-msi to noeffect. Then pip install pymsilib also no effect. -
I can't Go To Definition for pytest fixtures in Cursor (VSCode)
I am using Cursor. I cannot command-click into fixtures injected as parameters in my pytests. Command-clicking to any other variable, function, class works fine. I am working in a Django Ninja project. @pytest.mark.django_db def test_deleting_an_already_inactive_channel_raises_error(mock_auth, client, client_headers, user, channel): channel.active = False channel.save() url = reverse("roon:channel", kwargs={"channel_id": channel.id}) response = client.delete(url, content_type="application/json", headers=client_headers(user)) assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY In the above example, I cannot click into mock_auth, client, client_headers etc. Here is my vscode settings.json: { "python.testing.pytestEnabled": true, "python.testing.pytestArgs": ["--import-mode=importlib", "--no-cov"] } Here is my pyproject.toml: [tool.pytest.ini_options] minversion = "7.0" #Pytest to have verbose outputs #Pytest-xdist automatically determines number of workers based on cpu#Output a summary of all, except passes #Pytest report stats - Failures + Skipped #Pytest-cov to report coverage for library #Pytest-cov to use pyproject.toml file for additional coverage config #Pytest-cov outputs coverage to stdout #Pytest-cov fails if the coverage falls under the value #Pytest-cov generates an HTML report in /test-results #Pytest-cov generates an XML report in /test-results addopts = ''' -vv -n auto -ra -m "not (deprecated or integration)" --cov=api --cov-config pyproject.toml --cov-report term-missing --cov-fail-under=60 --cov-report html --cov-report xml --durations=10 -s ''' markers = [ "integration: marks tests for integration environment (deselect with '-m \"not integration\"')", "slow: marks … -
What could cause a Django webpage rendering on main domain but not subdomain and localhost?
I’m trying to solve an issue with djangoproject.com. The footer on the bottom right has a “Corporate Membership” link under “Support Us”. The “Corporate Membership” link works when the url is https://www.djangoproject.com/foundation/corporate-membership/%E2%80%9D but not in case of https://docs.djangoproject.com/foundation/corporate-membership/%E2%80%9D or https://dashboard.djangoproject.com/foundation/corporate-membership/%E2%80%9D. It also raises a Page not Found (404) error on the development server, like so I searched the repo and couldn't find any template for this link, if the template doesn't exist how is it rendering in production? urls/www.py from django.conf import settings from django.contrib import admin from django.contrib.auth import views as auth_views from django.contrib.contenttypes import views as contenttypes_views from django.contrib.flatpages.sitemaps import FlatPageSitemap from django.contrib.sitemaps import views as sitemap_views from django.urls import include, path, re_path from django.views.decorators.cache import cache_page from django.views.generic import RedirectView, TemplateView from django.views.static import serve from accounts import views as account_views from aggregator.feeds import CommunityAggregatorFeed, CommunityAggregatorFirehoseFeed from blog.feeds import WeblogEntryFeed from blog.sitemaps import WeblogSitemap from foundation.feeds import FoundationMinutesFeed from foundation.views import CoreDevelopers admin.autodiscover() sitemaps = { "weblog": WeblogSitemap, "flatpages": FlatPageSitemap, } urlpatterns = [ path("", TemplateView.as_view(template_name="homepage.html"), name="homepage"), path( "start/overview/", TemplateView.as_view(template_name="overview.html"), name="overview", ), path("start/", TemplateView.as_view(template_name="start.html"), name="start"), # to work around a permanent redirect stored in the db that existed # before the redesign: path("overview/", RedirectView.as_view(url="/start/overview/", permanent=False)), path("accounts/", include("accounts.urls")), … -
How can I trigger automatic actions when a model field (e.g. date) reaches a specific time like 5 days, weekly, or yearly?
I’m working on a Django-based app where developers can connect users to their apps using an account number. Once connected, a Subscription model is created with fields like user, plan, is_active, and next_billing_date. The next_billing_date depends on the plan type (weekly, monthly, yearly, etc.). I want to automatically take some action (e.g., disable is_active or charge again) when the next_billing_date is reached. This includes: Deactivating expired subscriptions Or triggering recurring billing based on subscription cycle (e.g. Jan 1, 2025 → Jan 1, 2026 for yearly, or weekly for others) I already store the next billing date like this: next_billing_date = timezone.now().date() + timedelta(days=30) # For monthly plans I was trying to use signals to handle things like automatically charging users after 7 days or ending a subscription after 1 month. But I realized that Django signals only work when a model is saved, updated, or deleted, not based on time passing. This means if I want something to happen exactly 7 days after a user subscribes, a signal won’t help unless something else triggers it (like the model being saved again). So even if the subscription is about to expire, Django won’t do anything automatically unless some code updates that … -
How can I secure my Dockerized Django + PostgreSQL app in production on a VPS using Nginx?
I’m using Django and PostgreSQL for my web project, which I’ve containerized using Docker. I run it on a VPS and serve it with Nginx (running outside Docker). I'm concerned about the security of my PostgreSQL database and want to make sure it's properly locked down. Specifically, I want to understand best practices to protect the database when: Docker containers are running in detached mode The PostgreSQL service is inside Docker Nginx is acting as the web entry point from the host My questions: How can I ensure my PostgreSQL container is not exposed to the public internet? What are Docker and PostgreSQL-specific security improvements I can apply? Are there any changes I should make in the following Dockerfile or docker-compose-prod.yml? My current Dockerfile FROM python:3.x.x # Set environment variables ENV PYTHONDONTWRITEBYTECODE=x ENV PYTHONUNBUFFERED=x WORKDIR /src # Install system dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ curl \ build-essential \ && rm -rf /var/lib/apt/lists/* # Install Poetry RUN curl -sSL https://install.python-poetry.org | python3 - && \ export PATH="/root/.local/bin:$PATH" # Add this line to make sure Poetry is in the PATH for subsequent commands ENV PATH="/root/.local/bin:$PATH" COPY pyproject.toml poetry.lock* ./ # # Install dependencies RUN poetry config virtualenvs.create … -
Unable to properly render ModelSelect2Multiple in modal window
i have a Book model that has a authors field which is a ManyToMany field to Author model. I'm using django-autocomplete-light package to render a select2 widget in my templates that will allow me to select more than one author when creating new books. (Using ModelSelect2Multiple) So the field renders OK in a regular html page. But when i try to render the same exact form in a DaisyUI modal window, the dropdown menu that it should open will be opened in the back of the modal window (like i can see it is being displayed behind the modal window). Here is my form: class BookForm(forms.ModelForm): class Meta: model = Book fields = ( 'title', 'authors', ) widgets = { 'authors': autocomplete.ModelSelect2Multiple( url=reverse_lazy('shop:authors-autocomplete') ) } Here is the modal container (followed the documentation from django-autocomplete-light): {% load static %} <dialog id="new_book_modal_container" class="modal"> <div class="modal-box"> <div id="response"> <strong>form will be placed here</strong> </div> </div> </dialog> <script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script> {{ form.media }} Here is the form template: {% load static %} <div> {% if form %} <form> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary btn-sm"> Submit </button> </form> {% endif %} </div> Using htmx, i open … -
Uppy with DO Storeages on Django
I have been fighting with this for hours. I can not get Uppy AWS to work. I am using DigitalOcean Storage. Here is the html. (part is Github Copilot) <script type="module"> import {Uppy, Dashboard, AwsS3} from "https://releases.transloadit.com/uppy/v4.13.3/uppy.min.mjs" const uppy = new Uppy() uppy.use(Dashboard, {target: '#uppy', inline: true}) .use(AwsS3, { getUploadParameters (file, options) { return fetch('/upload/uppy_s3').then((response) => response.json()) }, }) </script> Here is the backend view. client = boto3.client('s3', region_name='sgp1', endpoint_url='https://sgp1.digitaloceanspaces.com', aws_access_key_id=SPACES_KEY, aws_secret_access_key=SPACES_SECRET, config=Config(s3={'addressing_style': 'virtual'}), ) url = client.generate_presigned_url( ClientMethod='get_object', Params={ "Bucket": "mysite-bucket", "Key": "uppyfile.pdf", }, ExpiresIn=3600 ) return { "method": "PUT", "url": url, "headers": { "content-type": "application/pdf" }, } I have been working on this for hours and tried many combinations. right now I am getting: AttributeError: 'dict' object has no attribute 'status_code' I am not a javascript person so I am sure my errors are obvious to most of you. Most of this is via Copilot. the videos on youtube are outdated and don't work. Thank you so much. -
Django Admin ask for login on every click
Working on a Django project deployed on AWS. In production, I'm facing a session-related issue: When I open the Django admin site (/admin) and log in, everything works smoothly. But if I open the user site (/) in the same browser window and log in there, the admin gets logged out — which is expected behavior, so no complaints there. But here's the twist: Even after closing the user site tab, when I go back to the admin site and log in again, Django lets me into the admin dashboard — only to forget me immediately. Every time I try to do literally anything (open a model, add a record, even breathe)... Django hits me with: “Oh hey 👋 just checking — who are you again?” Then it redirects me right back to the login page. I log in. I click something. Back to login. I log in again. I blink. Login page. Again. It’s like Django has the memory of a goldfish 🐠. -
Python Wand: MagickReadImage returns false, but did not raise ImageMagick exception
I've got some long-standing code in a Django code base that reads in a PDF and uses Wand to take a screenshot of the first page of the PDF, which is then displayed on the website. We recently migrated servers (an upgrade from Ubuntu 22 LTS to 24 LTS), and something broke, and I can't for the life of me figure it out. First, some potentially useful information: OS: Ubuntu 24 LTS Python 3.12.3 Django 5.2.4 Wand 0.6.13 Web server: nginx 1.24.0 gunicorn version: 23.0.0 We are not using Docker. This Django app is running directly on the server with a local virtual environment. The PDF-to-PNG code is on the admin side of the web app. Here's the heart of it: with Image(filename=pdf_location) as pdf: with Image(pdf.sequence[0]) as first_page_pdf: with first_page_pdf.convert('png') as first_page_png: first_page_png.background_color = Color('white') first_page_png.alpha_channel = 'remove' return first_page_png.make_blob() When I upload a PDF to the admin site for processing, I'm getting this error: MagickReadImage returns false, but did not raise ImageMagick exception. This can occur when a delegate is missing, or returns EXIT_SUCCESS without generating a raster. I have tried everything I can think of after a ton of searching, but nothing is working: I do have … -
JavaScript Django default scaling using extends index
I'm using Django's template inheritance (extends) in every page of the app. The current design looks too zoomed out, and I want to adjust the default scaling through my index.html, but it didn't work. I also tried using custom CSS, but it still doesn't fix the issue. Does anyone have an idea how I can adjust the default scaling properly? I have this in my index.html <meta name="viewport" content="width=450, initial-scale=0.6, user-scalable=yes, minimum-scale=0.6, maximum-scale=0.6" /> -
Filter Django RangeField by comparing to a point, not to another range
The PostgreSQL specific model fields docs are very specific about how to compare one RangeField to another range. But how do you compare a range to a single point? For example, if I've got a model with valid_range=DateTimeRangeField, and I want to find all instances which are no longer valid, I need to do something like: from django.utils import timezone as tz MyProduct.objects.filter(valid_range__lt=tz.now()) But this isn't allowed. I thought I could use fully_lt but that's not allowed with a particular date either. How do I filter a DateTimeRangeField to find instances whose ranges ended before a certain datetime? -
502 Bad Gateway on AWS ELB with Nginx + Django + Gunicorn
Summary of Issue: 502 Bad Gateway from ELB to Django app behind Nginx + Gunicorn on EC2 Environment: Hi, I wonder if anyone can assist. I've been banging my head against a wall for over a week now, I've tried two different AI's and reviewed everything I can find here and on AWS. I have an Elastic Load Balancer (Application) and Auto Scaling Group. Everything is set up in line with best practice, html and php pages are served up fine. However django is not served to the public side of the ELB, it returns a 502 Bad Gateway. • AWS Elastic Load Balancer (ELB) in front of EC2 instance • ELB terminates HTTPS, forwards HTTP (port 80) to Nginx on EC2 • Nginx configured as reverse proxy forwarding /app/ requests to Gunicorn via Unix socket • SELinux is set as Permissible • Django app served by Gunicorn, running on EC2 • Nginx version 1.28.0, Gunicorn serving Django app on Unix socket /tmp/gunicorn_.sock • Django app uses virtual environment with dependencies installed per deployment script Observed Behavior: • curl -vk https:///test (simple Nginx endpoint) returns HTTP 200 OK correctly • curl --unix-socket /tmp/gunicorn_.sock http:///app/ returns HTTP 200 OK correctly — … -
How to use pytes fixtures in single Django TestCase testfunction
Test yields TypeError: test() missing 1 required positional argument: 'fix' from django.test import TestCase import pytest @pytest.fixture def fix(): return "x" class QueryTestCase(TestCase): def test(self, fix): print(fix) An almost similar case exists but I want the fixture to be used only in that particular test but not the class -
importing files twice from multiple files
imagine i have a "first.py" file with some code in it , and then i import it in another python file called "secend.py" then i import the "secend.py" file & the "first.py" into "third.py" file ,, Will this cause an performance problems? (For example, a file is imported twice inside another file .. ?) I always run into this problem in Django projects.(if it is a problem) for example i have my models file and i import the models file into serialazers file and then i import both models & serializers file into views file maybe im anot the best person at drawing things but there is a kinda stupid schematic that shows what im talking about! : -
Where are these PydanticDeprecatedSince20 and RemovedInDjango60Warning warnings coming from?
I am getting the following output in my warnings summary: venv/lib/python3.11/site-packages/pydantic/_internal/_config.py:323: 15 warnings /Users/darshankalola/Desktop/roon-be/roon-doctor-service/.venv/lib/python3.11/site-packages/pydantic/_internal/_config.py:323: PydanticDeprecatedSince20: Support for class-based `config` is deprecated, use ConfigDict instead. Deprecated in Pydantic V2.0 to be removed in V3.0. See Pydantic V2 Migration Guide at https://errors.pydantic.dev/2.11/migration/ warnings.warn(DEPRECATION_MESSAGE, DeprecationWarning) .venv/lib/python3.11/site-packages/django/db/models/fields/__init__.py:1148: 15 warnings /Users/darshankalola/Desktop/roon-be/roon-doctor-service/.venv/lib/python3.11/site-packages/django/db/models/fields/__init__.py:1148: RemovedInDjango60Warning: The default scheme will be changed from 'http' to 'https' in Django 6.0. Pass the forms.URLField.assume_scheme argument to silence this warning, or set the FORMS_URLFIELD_ASSUME_HTTPS transitional setting to True to opt into using 'https' as the new default scheme. return form_class(**defaults) -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html Results (7.89s): 45 passed I have searched and ensure that none of my tests are producing these warnings. In fact I have no idea where they are coming from. I have updated required packages to their latest versions, and have corrected instances of deprecated functionality. -
Replacement for migrate --skip-checks
I am having some issues with the latest version of Django. It seems they have removed the --skip-checks option from the manage.py migrate command. The problem I am getting is that the app (that was working on 4.2) is trying to check the database tables (site_settings) before they exist. What is the right way to initially migrate data in Django 5.2.4 ? The error that I get now when running any manage.py command is: django.db.utils.ProgrammingError: relation "site_settings_setting" does not exist -
htmx web socket extension not rendering server messages
I'm using the below to render model initial counts on load. consumers.py: from channels.generic.websocket import WebsocketConsumer from django.template.loader import render_to_string from myapp.models import Model1, Model2, Model3, Model4 class DashboardHeaderConsumer(WebsocketConsumer): def update_dashboard_counts(self): stats = [ {'name': 'Model1', 'value': Model1.objects.count()}, {'name': 'Model2', 'value': Model2.objects.count()}, {'name': 'Model3', 'value': Model3.objects.count()}, {'name': 'Model4', 'value': Model4.objects.count()}, ] html = render_to_string('dashboard/header-stats.html', {'stats': stats}) self.send(text_data=html) def connect(self): self.accept() self.update_dashboard_counts() header-stats.html: {% for stat in stats %} <div class="col-sm-6 col-xl-3"> <div class="dashboard-stat rounded d-flex align-items-center justify-content-between p-4"> <div class="ms-3"> <p class="mb-2">{{ stat.name }}</p> <h6 class="mb-0">{{ stat.value }}</h6> </div> </div> </div> {% endfor %} my-template.html: {% load static %} {% block styles %} <link rel="stylesheet" href="{% static 'css/dashboard.css' %}"> {% endblock %} <div class="container-fluid pt-4 px-4"> <div class="row g-2 mb-2 stats-wrapper" hx-ext="ws" ws-connect="/ws/dashboard/header/" hx-target=".stats-wrapper" hx-swap="innerHTML" > </div> <div class="active-tasks-scroll-container"> <div class="row flex-nowrap g-2"> </div> </div> </div> I'm expecting the counts to show up. However, despite the message is received and can be seen in under the networks websocket request, the dom is empty. This is what gets rendered: <html lang="en" data-bs-theme="dark"> <head> <meta charset="UTF-8"> <title>App Title</title> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <link href="/static/css/index.css" rel="stylesheet"> <script src="/static/js/bootstrap.bundle.min.js"></script> <script src="/static/js/htmx.min.js"></script> <script src="/static/js/htmx-ext-ws%402.0.2"></script> <style> .htmx-indicator { opacity: 0 } .htmx-request .htmx-indicator { opacity: 1; transition: … -
Django + Tailwind CSS deployment failing on Railway with Procfile parsing errors
I'm trying to deploy a Django application with compiled Tailwind CSS to Railway, but I keep getting Procfile parsing errors. The build process works fine (Tailwind compiles successfully), but the deployment fails during the Procfile parsing stage. Error Message Nixpacks build failed Error: Reading Procfile Caused by: found unknown escape character at line 1 column 44, while parsing a quoted scalar My Setup Project Structure: Jobflow/ ├── manage.py ├── Procfile ├── requirements.txt ├── package.json ├── tailwind.config.js ├── static/ │ └── css/ │ ├── input.css │ └── output.css (generated) ├── Jobflow/ │ ├── settings.py │ ├── wsgi.py │ └── urls.py └── JobFlow_app/ ├── models.py ├── views.py └── templates/ Current Procfile content: web: python manage.py runserver 0.0.0.0:$PORT requirements.txt: Django==4.2 python-decouple==3.8 gunicorn==21.2.0 whitenoise==6.6.0 psycopg2-binary==2.9.9 Pillow==10.1.0 dj-database-url==2.1.0 package.json scripts: { "scripts": { "build-css": "npx tailwindcss -i ./static/css/input.css -o ./static/css/output.css --watch", "build-css-prod": "npx tailwindcss -i ./static/css/input.css -o ./static/css/output.css --minify", "dev": "npm run build-css", "build": "npm run build-css-prod" }, "devDependencies": { "tailwindcss": "^3.4.0" } } What Works ✅ Tailwind CSS compilation - Build logs show: > npx tailwindcss -i ./static/css/input.css -o ./static/css/output.css --minify Rebuilding... Done in 417ms. ✅ Python dependencies installation - No errors during pip install ✅ Static file structure - All files are in … -
404 not found error Django URL with JavaScript fetch function
I'm building a Todo app with Django and JavaScript. I've reached the point where when I click a "trash" button, the note should be deleted, but it shows an error in the console, the reason for which is not clear to me, since I specified the correct URL path. The error is appears when I click the "trash" button. urlpatterns = [ path('', views.index, name="index"), path('add_note/', views.add_note, name="add_note"), path('del_note/<int:id>/', views.del_note, name="del_note"), ] Django view function for deleting a note is also created. @require_POST def del_note(request, id): del_obj = get_object_or_404(Note, id=id, user=request.user) del_obj.delete() return JsonResponse({"status": 200, "message": "Note deleted"}) And here is the HTML of the list with that "trash" button. <ul class="todo__list"> {% for note in notes %} <li class="todo__note flex" data-id="{{ note.id }}"> <div> <input type="checkbox" /> <span>{{ note.text }}</span> </div> <div class="delete__edit"> <button class="edit-btn" id="editBtn" type="button"> <img src="{% static 'images/edit.svg' %}" alt="" /> </button> <button class="delete-btn" id="deleteBtn" type="button"> <img src="{% static 'images/delete.svg' %}" alt="" /> </button> </div> </li> {% endfor %} </ul> And this is JS fetch function for send request to django urls "del_note" path. const noteList = document.querySelector(".todo__list"); //const delUrl = document.body.dataset.delNoteUrl; function getCSRFToken() { const tokenInput = document.querySelector("input[name='csrfmiddlewaretoken']"); return tokenInput ? tokenInput.value : ""; } … -
Django "makemigrations" stuck for ever
When I run python manage.py makemigrations, it just gets stuck. No matter how long I wait, it stays frozen forever—no logs, no output, nothing. I even changed my PostgreSQL database to the default SQLite database in settings.py, but it still didn’t help. Please help me out. I expected python manage.py makemigrations to detect my model changes and generate migration files. Instead, it just gets stuck with no output, logs, or errors—completely frozen. Here’s what I’ve tried so far: Switched from PostgreSQL to the default SQLite DB in settings.py to rule out DB-related issues. Deleted all old migration files (except init.py) and tried running makemigrations again. Cleared all pycache and .pyc files. Rebuilt the virtual environment from scratch and reinstalled all dependencies. Simplified the models (removed unnecessary fields, used proper types like DateTimeField instead of CharField for dates). Tried isolating the models in a new Django app within the same project. Ran makemigrations --verbosity 3 and --dry-run, but still no output or detection. Even created a brand new Django project and app with a minimal model, and it still gets stuck when running makemigrations. At this point, I’m not sure if it’s Django, my environment, or something corrupted deep in the … -
Django filter an m2m relation by a list of inputs (which must all match)
Let's take some Store and Book models as examples: class Book(Model): title = CharField(...) ... class Store(Model): books = ManyToManyField('Book', blank=True, related_name='stores') .... I receive a list of book titles and must return stores linked to those books. I need the option for both an AND query and an OR query. The OR query is rather simple; we only need a store to match once: Store.objects.filter(book__title__in=book_titles) However the AND query seems tricky. Perhaps I am simply too deep to notice, but so far I have only managed by chaining queries which is not very good, at least performance-wise. from django.db.models import Q filtering = Q() for book_title in book_title_list: filtering &= Q(id__in=Book.objects.get(title=book_title).stores) Store.objects.filter(filtering) This effectively creates an OUTER JOIN and a SELECT within the WHERE clause for every book title, which at 2 or 3 is not much but definitely not advisable when user input is not limited. Without explicitly looping and adding Q objects like this I have yet to obtain a query that actually works. More often than not, the query either only evaluates a single line of the m2m relation or behaves similarly to the OR query. As a reminder, the AND query needs all returned stores … -
how I push Django database sqlite3 and media folder on github for production server
The problem occurs when I delete the db.sqlite3 and media on .gitignore file. and write add command git add -A. the error comes fatal:adding files fail PS C:\Users\user\OneDrive - Education Department, Government of Punjab\Desktop\Django demos\Blog> git add -A error: read error while indexing media/uploads/23/09/21/web_extol_college.jpg: Invalid argument error: media/uploads/23/09/21/web_extol_college.jpg: failed to insert into database error: unable to index file 'media/uploads/23/09/21/web_extol_college.jpg' fatal: adding files failed -
Django REST Framework `pagination_class` on ViewSet is ignored
Describe the Problem I have a ModelViewSet in Django REST Framework designed to return a list of Order objects. To improve performance, I'm trying to implement custom pagination that limits the results to 65 per page. Despite setting the pagination_class property directly on my ViewSet, the API endpoint continues to return the full, unpaginated queryset (over 300 objects). It seems my custom pagination class is being completely ignored. My goal is for the API to return a paginated response with a count, next, previous, and a results list containing a maximum of 65 items when I request .../api/orders/?page=1. What I Tried Here is my setup: 1. pagination.py: I created a custom pagination class. # my_app/pagination.py from rest_framework.pagination import PageNumberPagination class CustomOrderPagination(PageNumberPagination): page_size = 65 page_size_query_param = 'page_size' max_page_size = 100 2. views.py: I assigned this custom class to my ViewSet. The queryset uses select_related and prefetch_related for performance. # my_app/views.py from rest_framework import viewsets from django.db.models import Sum from .models import Order from .serializers import OrderSlimSerializer from .pagination import CustomOrderPagination class OrderViewSet(viewsets.ModelViewSet): # I explicitly set the pagination class here pagination_class = CustomOrderPagination serializer_class = OrderSlimSerializer queryset = Order.objects.select_related('client').prefetch_related( 'orderitem_set__location__service_plan' ).annotate( total_amount=Sum('orderitem_set__service_plan__service_fee') ) # ... (permission_classes, filter_backends, etc.) ... 3. … -
getCSRFToken is not defined error, JavaScript
This is the part of the code in the Django + JavaScript Todo App that is responsible for deleting a note. I need a csrftoken for this, but the JS is showing me an error in the console. What did I do wrong and how can I fix it? Uncaught ReferenceError: getCSRFToken is not defined at HTMLButtonElement.<anonymous> (main.js:100:30) const delUrl = document.body.dataset.delNoteUrl; deleteBtn.addEventListener("click", (e) => { e.preventDefault(); if (e.target.classList.contains("delete-btn")) { const parentLi = e.target.closest(".todo__note"); const noteId = parentLi.getAttribute("data-id"); fetch(`${delUrl}/${noteId}`, { method: "POST", headers: { "X-CSRFToken": getCSRFToken(), }, }) .then((response) => response.json()) .then((data) => { if (data.status == "success") { parentLi.remove(); } }); } });``` Here is HTML, if need. <ul class="todo__list"> {% for note in notes %} <li class="todo__note flex" data-id="{{ note.id }}"> <div> <input type="checkbox" /> <span>{{ note.text }}</span> </div> <div class="delete__edit"> <button class="edit-btn" id="editBtn"> <img src="{% static 'images/edit.svg' %}" alt="" /> </button> <button class="delete-btn" id="deleteBtn"> <img src="{% static 'images/delete.svg' %}" alt="" /> </button> </div> </li> {% endfor %} </ul>