Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send real emails via Gmail SMTP in Cookiecutter Django project?
I'm using Cookiecutter Django for my project, and I’d like to start sending real emails through Gmail SMTP (not just to Mailpit) — for example, welcome emails after user registration. Right now, in local.py, email is configured like this: EMAIL_HOST = env("EMAIL_HOST", default="mailpit") EMAIL_PORT = 1025 This works fine for local testing — emails show up in Mailpit at localhost:8025. But now I want to send real emails to users via Gmail when running in production (or even temporarily in development for testing real delivery). I already have Gmail App Passwords set up and my .envs/.production/.django file contains: EMAIL_HOST_USER=something@gmail.com EMAIL_HOST_PASSWORD=my-app-password DEFAULT_FROM_EMAIL=something@gmail.com And in production.py, I have: EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.getenv("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = os.getenv("EMAIL_HOST_PASSWORD") DEFAULT_FROM_EMAIL = os.getenv("DEFAULT_FROM_EMAIL") My questions: Is this the correct way to send real emails using Gmail SMTP in Cookiecutter Django? Is there anything else I need to do to make this work in production? Can I test Gmail sending locally without breaking the Cookiecutter setup? Thanks in advance! -
Okta Redirection based on attribute then access SubPage
I have a successfully authenticated and got redirected to my role let's say Admin page, in my Okta it is called http://test.com/myAdmin I have other redirects depending on the users roles; however, that those work as well and their URI are: http://test.com/myOtherRole1 http://test.com/myOtherRole2 I am perplexed because when I go to access let's say from my Django routes from urls.py: url_patterns=[ ..., path("myAdmin/", views.Adminrole, name="Admin_Home"), path("myAdmin/mainpanel", views.mainpanel, name="view"), ] I cannot do so after Okta sign-in and landing on http://test.com/myAdmin. So the next page I should be able to access is: http://test.com/myAdmin/mainpanel I am expecting to access each subdomain in each route in urls.py. Does that mean I have to include them in Okta Redirect URI? Because I keep getting an error 403 when I try to advance to other pages. -
Problems with Django admin model page. Slow performance
I have a problem with a change view of an model in Django. I have profiled the endpoint with different tools, and also took logs of the database queries run using shell plus. I can't see any long calls on the pg db and the cprofiler tool i used shows no long calls in the stack trace , but the response takes longer than 3 mins and i can't find a way to debug it. I also inspected Django source code ModelAdmin and changeform_view it seems to not have slow performance issues there it returns immediately . Any help ? -
DigitalOcean App Platform does not parse ${db.DATABASE_URL} after bulk editor changes
I am using DigitalOcean App Platform to deploy a Django app. The initial deployment worked fine, but I've attempted to use the bulk editor on the component-level environment variables, and since then, the deployment fails when executing dj_database_url.config(default=config('DATABASE_URL'). For debugging, I added this line to settings.py: print(f"[BUILD DEBUG] DATABASE_URL = {repr(os.environ.get('DATABASE_URL'))}") This returns [BUILD DEBUG] DATABASE_URL = '${db.DATABASE_URL}' in the build logs. I don't understand why the environment variable is not resolving. My app spec looks like this: services: - environment_slug: python envs: - key: DATABASE_URL scope: RUN_AND_BUILD_TIME value: ${db.DATABASE_URL} Could this be a bug, or am I doing something wrong? Yes, my database is named correctly: databases: - engine: PG name: db The only thing that changed between my last deployment and this failed deployment, besides a few lines of code, is that I used the bulk editor to add new environment variables. Some of the existing environment variables were encrypted, but they look OK in the app spec. -
Passing Arguments to Django Views From a Rendered Page
I've been tasked to build web-based front end to an existing MySQL database. I'm new to web development in general, decided to use Django because I'm a pretty advanced Python user. However, I'm completely stuck doing what seems like it should be a pretty common task. The database holds information about Software Bill of Materials (SBOMs) and the pieces of software associated with each. Right now, all I want to do is have the user select an SBOM from the database, retrieve the software associated with that SBOM, and display the results. I would like the user to be able to page through the results. I'm trying to do this by rendering a list of SBOMs in the system in HTML, with each entry having an associated button that will pass the selected parameters to the next view in line. As far as I can tell, I have things set up so Here's how my urls.py is set up: urlpatterns = [ path("", views.select_bill, name="select_bill"), path("select_software/<int:bill_num>", views.select_software, name="select_software"), path("select_software/<int:bill_num>/<int:page>", views.select_software, name="select_software") ] my views.py: from django.shortcuts import render from django.core.paginator import Paginator from frontend.models import SoftwareResults RESULTS_PER_PAGE = 25 def select_bill(request): bills = get_bills() # Function that queries the existing … -
Django annotate with ExtractMonth and ExtractYear doesnt extract year
I have this model: class KeyAccessLog(models.Model): key = models.ForeignKey( Key, related_name="access_logs", on_delete=models.CASCADE ) path = models.CharField(max_length=255) method = models.CharField(max_length=10) ip_address = models.GenericIPAddressField() created = models.DateTimeField(auto_add_now=True) class Meta: verbose_name = "Key Access Log" verbose_name_plural = "Key Access Logs" ordering = ("-pk",) indexes = [ models.Index( models.Index( "key", ExtractMonth("created"), ExtractYear("created"), name="key_month_year_idx", ), ), ] def __str__(self): return f"{self.key} - {self.path} - {self.method}" My point is to use the declared index when filtering by key, month, and year but the query that is generated from ORM is not extracting as it does for the month. dt_now = timezone.now() qs = api_key.access_logs.filter(created__month=dt_now.month, created__year=dt_now.year) print(qs.query) gives me: SELECT "public_apikeyaccesslog"."id", "public_apikeyaccesslog"."api_key_id", "public_apikeyaccesslog"."path", "public_apikeyaccesslog"."method", "public_apikeyaccesslog"."ip_address", "public_apikeyaccesslog"."created" FROM "public_apikeyaccesslog" WHERE ( "public_apikeyaccesslog"."api_key_id" = 1 AND EXTRACT( MONTH FROM "public_apikeyaccesslog"."created" AT TIME ZONE 'UTC' ) = 5 AND "public_apikeyaccesslog"."created" BETWEEN '2025-01-01 00:00:00+00:00' AND '2025-12-31 23:59:59.999999+00:00' ) ORDER BY "public_apikeyaccesslog"."id" DESC Now I tried explicitly to annotate extracted month and year: dt_now = timezone.now() qs = api_key.access_logs.annotate( month=ExtractMonth("created"), year=ExtractYear("created") ).filter(month=dt_now.month, year=dt_now.year) print(qs.query) this gives me almost the same SQL: SELECT "public_apikeyaccesslog"."id", "public_apikeyaccesslog"."api_key_id", "public_apikeyaccesslog"."path", "public_apikeyaccesslog"."method", "public_apikeyaccesslog"."ip_address", "public_apikeyaccesslog"."created", EXTRACT( MONTH FROM "public_apikeyaccesslog"."created" AT TIME ZONE 'UTC' ) AS "month", EXTRACT( YEAR FROM "public_apikeyaccesslog"."created" AT TIME ZONE 'UTC' ) AS "year" FROM "public_apikeyaccesslog" … -
Custom id generation on bulk_create in django
I want different models in my django project to have different prefixes (like usr_ for user, acc_ for account etc.) I then want to append a nanoid to this prefix. I defined a basemodel which is used by all the other models and I overrode the basemodel's save method to create the id in the format I want. But the issue is that when I use bulk_create the ids are not in the format I want. What is the easiest way that I can generate my custom ids in bulk_create that can be used by all other models. -
How can I link multiple Django model tables as if they were one when entering data?
Good morning! I am a bit new to Django. I wanted to ask about the relationships between Django model tables. I have several Django model tables. They should all belong to the same correspondence - a row from one table - is respectively related to a row from another table. That a row from one model table is also and, respectively, a row from another model table - they belong to and characterize one object. This is how I split one large table into several. How can I make the tables related and - so that when filling in only one form through the Django model form - other related tables are also automatically filled in. How can I form a single QuerySet or DataFrame from these several respectively related model tables. How can I automatically send data not only to one table but also to others when sending data from the Django model form, which are related to several Django model tables as if they were one when entering data? How can I link multiple Django model tables as if they were one when entering data? class MyModel(models.Model): id = models.AutoField(primary_key=True) # Auto-incrementing integer uuid = models.UUIDField(default=uuid.uuid4) name = … -
Could not find backend 'storages.backends.s3boto3.S3StaticStorage'
When deploying my Django app it just (seems like) stopped to connect to my S3 bucket. The full message I get when running collectstatic is Traceback (most recent call last): File "/home/ubuntu/campmanager/manage.py", line 22, in <module> main() File "/home/ubuntu/campmanager/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/management/base.py", line 416, in run_from_argv self.execute(*args, **cmd_options) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/management/base.py", line 460, in execute output = self.handle(*args, **options) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 184, in handle if self.is_local_storage() and self.storage.location: File "/home/ubuntu/.local/lib/python3.10/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 245, in is_local_storage return isinstance(self.storage, FileSystemStorage) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/utils/functional.py", line 280, in __getattribute__ value = super().__getattribute__(name) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/utils/functional.py", line 251, in inner self._setup() File "/home/ubuntu/.local/lib/python3.10/site-packages/django/contrib/staticfiles/storage.py", line 542, in _setup self._wrapped = storages[STATICFILES_STORAGE_ALIAS] File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/files/storage/handler.py", line 34, in __getitem__ storage = self.create_storage(params) File "/home/ubuntu/.local/lib/python3.10/site-packages/django/core/files/storage/handler.py", line 45, in create_storage raise InvalidStorageError(f"Could not find backend {backend!r}: {e}") from e django.core.files.storage.handler.InvalidStorageError: Could not find backend 'storages.backends.s3boto3.S3StaticStorage': Module "storages.backends.s3boto3" does not define a "S3StaticStorage" attribute/class This is my setting in settings.py STATIC_ROOT = os.path.join(CORE_DIR, 'staticfiles') STATIC_URL = 'static/' AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_DEFAULT_ACL = 'public-read' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_MEDIA_LOCATION = 'media-dev' MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_MEDIA_LOCATION) … -
React front_end & Django back_end Login functionality
I created react front end first then i create a django app and project for back end in the front end back end connected by Django REST framework and jwt and serializers the django back_end and api can send a json for validate the login in api end point but still i cant get this done so i use gemini Api as code assistant we both worked for hours and the end the gemini say's i'm exhausted , is any know how to connect react front end and Django for back end [enter image description here](https://i.sstatic.net/fzyhg3p6.png) -
Updated from Django 3.2 to 5.2, now I'm getting "Obj matching query does not exist"
I'm using Django in a non-Django project (Postgresql 17 under the hood) purely to make my unit tests easier. I've defined all my models like this: class Bar(models.Model): internal_type = models.TextField(...) ... class Meta: managed = False db_table = 'myschema\".\"bar' class Foo(models.Model): ... bar = models.ForeignKey('Bar', models.DO_NOTHING, db_column='bar', blank=True, null=True) class Meta: managed = False db_table = 'myschema\".\"foo' This looks funky, but it was working perfectly fine on Django 3.2. It allowed me to write tests like this: def test_foo(self): from app import models assert models.Foo.objects.count() == 0 # self.cursor is a psycopg2 cursor # run_planner uses that cursor to create a bunch of Foo and related Bar objects run_planner(self.cursor) self.cursor.connection.commit() my_foos = models.Foo.objects.filter(bar__internal_type='special') assert my_foos.count() == 2 # this passes for m in my_foos: print(m.bar) # this raises DoesNotExist This test passes with no issues on Django 3.2, but fails on that last line on 5.2. How can I work around this? It seems like Django is using some stricter transaction isolation behind the scenes? How can the .count() succeed, but the accessing it fail? Note that my_foos specifically asks for Foo objects with related Bar instances. I've tried committing Django's cursor before, closing its connection and forcing it … -
I'm trying to integrate Google SSO into my Django app, but I keep running into an issue
I'm 99% sure it has to do with my custom authentication model, as shown below: from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model from django.db.models import Q UserModel = get_user_model() class UsernameOrEmailBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = UserModel.objects.get(Q(username__iexact=username) | Q(email__iexact=username)) except UserModel.DoesNotExist: return None else: if user.check_password(password) and self.user_can_authenticate(user): return user return None The goal was to allow users to sign in with a combination of email/username or password. But now, when i try to integrate Google SSO, it always redirects to the allauth signup page because Google doesn't provide a username. -
How to get a moving average (or max) in time period using Django ORM
I am trying to work out if it's possible/practical to use the Django ORM to get the highest value in an arbitrary timebox out of the database. Imagine a restaurant orders ingredients every day, we might have a simple model that looks like: class Order(models.Model): date = models.DateField() ingredient = models.CharField() quantity = models.IntegerField() Then I am able to get the sum quantities ordered each week: Order.objects.filter(date__gte=start_date, date__lt=end_date) .annotate(date=TruncWeek("date")) .values("ingredient", "date") .annotate(total=Sum("quantity")) .order_by("ingredient") But now I want to figure out the maximum quanity of each ingredient that has been ordered in any consecutive 7 (or X number of) days, across the filtered date range. Is it possible to do this in the ORM? -
modeltranslation ignores LANGUAGE setting
I have a djnago project where I use modeltranslation with 2 languages. I have defined LANGUAGES = .. in setting and added to installed_apps all apps from project and modeltranslation. The problem is that get_translation_fields() funtion from modeltranslation returns correct 2 languages for apps/general but returns all languages for apps/common and both apps are defiened the same. I have a resource that use this get_translation_fields() and it works well in apps/general but not in apps/common. -
Django django-admin-async-upload returns 302 redirect to 404 page in staging environment
I'm using the django-admin-async-upload library to handle asynchronous file uploads in my Django project. Everything works perfectly in my local development environment. However, when I deploy to the staging environment, attempting to upload a file results in a 302 redirect, which then leads to our custom 404 page. In the browser's network tab, I see a 302 Found status code, and the Location header points to our 404 page. I've ensured that the admin_async_upload URLs are included in our urls.py, and the app is added to INSTALLED_APPS. I'm not sure why this is happening only in the staging environment. Any insights or suggestions would be greatly appreciated. -
Using the Django REST Framework, how can I set a field to be excluded from one view, but included in an other, without much bloat code?
For example, if I had these models, how can I make sure that only the name of the house is displayed in one view, and all of it's properties are displayed in an other. Also, how can I display the realtor's name, and not only it's ID when I'm querying for a house? class Realtor(models.Model): name = models.CharField(max_length=100) class House(models.Model): name = models.CharField(max_length=100) address = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) realtor = models.ForeignKey(Realtor, related_name='houses', on_delete=models.CASCADE) -
How to handle existing data when introducing an intermediate model between a base model and a child model in a Django Polymorphic inheritance hirarchy
Current models: class Task(PolymorphicModel): pass class DownloadTask(Task): pass New models: And now i want to do add a new layer called VirtualTask: class Task(PolymorphicModel): pass class VirtualTask(Task): pass class DownloadTask(VirtualTask): pass Migration it looks like this: class Migration(migrations.Migration): dependencies = [ ("tasks", "0005_alter_task_last_error"), ] operations = [ migrations.CreateModel( name="VirtualTask", fields=[ ( "task_ptr", models.OneToOneField( auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to="tasks.task", ), ), ], options={ "abstract": False, "base_manager_name": "objects", }, bases=("tasks.task",), ), migrations.RemoveField( model_name="downloadtask", name="task_ptr", ), migrations.AddField( model_name="downloadtask", name="virtualptask_ptr", field=models.OneToOneField( auto_created=True, default=1, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to="tasks.virtualtask", ), preserve_default=False, ), ] “How should I handle existing data when inserting a new intermediate model (VirtualTask) between a base model (Task) and its subclasses in Django should I customize the migration file, and if so, what would be the step-by-step approach?” -
Django Forms - How can I update a form with a disabled required field?
I have a Django Model with one required field (shpid). I want to set this field to disabled when updating the form. Although the value of this field is shown and disabled when the template is first displayed I get a crispy-forms error saying 'this field is required' with the field showing empty when I try and update. I'm using crispy-forms and FormHelper to style the page. The relevant part of forms.py is: class UpdateShpForm(ModelForm): class Meta: model = Shipment fields = '__all__' widgets = { "shpid": TextInput(attrs={'disabled':False,'style':'max-width:120px'}), <=== Note diabled attribute "costs": TextInput(attrs={'style':'max-width:200px'}), "coldate": DateInput(attrs={'type': 'date','style':'max-width:180px'}), "deldate": DateInput(attrs={'type': 'date','style':'max-width:180px'}), "sts_date": DateInput(attrs={'type': 'date','style':'max-width:180px'}), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['shpid'].label = "Shipment ID" self.fields['awb'].label = "AWB" self.fields['pod'].label = "POD" self.fields['coldate'].label = "Collection Date" self.fields['deldate'].label = "Delivery Date" self.fields['recipient'].label = "Recipient" self.fields['status'].label = "Status" self.fields['sts_date'].label = "Status Date" self.fields['costs'].label = "Costs" self.helper = FormHelper() self.helper.layout = Layout( Row ( Column('shpid',css_class='form-group col-md-3 mb-0 pe-4'), Column('status',css_class='form-group col-md-3 mb-0 ps-2 pe-2'), Column('sts_date', css_class='form-group col-md-3 mb-0 ps-4'), ), Row( Column('awb',css_class='form-group col-md-6 mb-0 pe-4'), Column('pod',css_class='form-group col-md-6 mb-0 pe-4'), ), Row( Column('coldate', css_class='form-group col-md-3 mb-0 pe-4'), Column('deldate', css_class='form-group col-md-3 mb-0 ps-2 pe-2'), Column('recipient', css_class='form-group col-md-3 mb-0'), ), Field('costs'), ButtonHolder( Submit('submit', 'Update Shipment', css_class='ms-5 px-3 fw-bold'), css_class='center' … -
Wagail wont show Preview mode for pages on live server
Preview works fine locally but not on server.. I get the following error in browser console Error invoking action "load->w-preview#replaceIframe" SecurityError: Failed to read a named property 'scroll' from 'Window': Blocked a frame with origin "https://chandankhatwani.pythonanywhere.com" from accessing a cross-origin frame. at b.invokeWithEvent (vendor.fa6060f71148.js:2:6945) at b.handleEvent (vendor.fa6060f71148.js:2:6277) at r.handleEvent (vendor.fa6060f71148.js:2:1138) -
Permission Denied while building Django project with Docker
I'm trying to build Django project with Docker but I always get this error and don't know how to handle it: /usr/local/lib/python3.13/site-packages/django/core/management/commands/makemigrations.py:160: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': unable to open database file There is more errors down the line but all of them are about permission to create db.sqlite3 database. docker-compose.yml: version: "3.9" services: puppint: build: . container_name: puppint_app ports: - "8000:8000" volumes: - .:/app - ./static:/app/static env_file: - ./api.env working_dir: /app command: > sh -c "python puppint.py" Dockerfile: FROM python:3.13-slim AS builder RUN mkdir /app WORKDIR /app ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 RUN pip install --upgrade pip COPY requirements.txt /app/ RUN pip install --no-cache-dir -r requirements.txt FROM python:3.13-slim RUN useradd -m -r appuser && \ mkdir /app && \ chown -R appuser /app COPY --from=builder /usr/local/lib/python3.13/site-packages/ /usr/local/lib/python3.13/site-packages/ COPY --from=builder /usr/local/bin/ /usr/local/bin/ WORKDIR /app COPY --chown=appuser:appuser . . ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 USER appuser EXPOSE 8000 CMD ["python3 puppint.py"] puppint.py is a script which start makemigration and migrate stuff. I've created it mainly for checking whether the user is superuser or not and for the comfort of the user. puppint.py: import os import subprocess from time import sleep os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'puppint.settings') import django … -
Server requirements to host Django + MySQL + Media Files
I have developed an django based fully dynamic web application. Now I am deploying it & facing issue with the compatibility of the droplets. How much vCPUs required? How much RAM required? How much Storage required? I have deployed it with 1 GB RAM, 1 vCPU, 25 GB of storage. After sometime everything got stuck & many conflicts happened on the server I am expecting detailed configuration requirements to host a Django based application. -
Why does my Django website show 'Future home of something quite cool' after hosting on GoDaddy
"Whenever I host my website on GoDaddy.com and click on the homepage, it shows a message: 'Future home of something quite cool.'" -
Making Headless Website backend in Django, files are becoming lengthy and unreadable, is there any better and scalable approach?
I am working on a headless website project, where I am implementing the backend through django using django-rest-frameworks, till now I was using this structure my_project/ ├── manage.py ├── my_project/ │ ├── __init__.py │ ├── asgi.py │ ├─ settings.py │ ├─ urls.py │ ├── wsgi.py ├── auth/ ├── migrations/ │ └── __init__.py ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── tests.py ├── urls.py ├── signals.py ├── serializers.py ├── utils.py └── views.py But the problem I felt here is, after having so many APIView classes for login, registration, authentications, Googleauth etc.. the views.py file is getting lengthy and unreadable. So I am thinking to switch to this architecture (inspired from react js, where we can have all html, tailwind and js inside one component.jsx). my_project/ ├── manage.py ├── my_project/ │ ├── __init__.py │ ├── asgi.py │ ├─ settings.py │ ├─ urls.py │ ├── wsgi.py ├── auth/ ├── migrations/ │ └── __init__.py ├── api/ │ └── views/ ├── __init__.py │ ├── login.py │ └── register.py ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── tests.py └── urls.py Where for login API functionality, I will have login.py, and inside it I will store: Its serializer class for verifications. Its util class for … -
Form Tools Summary page redirection
I am not able to post all the code however I will try my best to explain and hopefully someone will be able to assist! I am using Django's formtools. I have four sections of a form, they are each their own (NamedUrlSessionWizardView, FormPreview) wizard. I am passing around the object id through session and DB retrieval as there is some logic around the object being deleted if the user goes back at a certain page. Once a user has completed a section of the form they are shown a summary of the answers they have provided. Once they have submitted on the summary page this data gets written to the DB and the user is directed back to a tracker page showing them that the section is now completed. If the user were to click into the section that is completed I would need to show them the summary page again. This is all working as intended. However when the section has been completed and the user gets displayed the summary information if they hit submit again the user gets redirected to the start of that form section, where as i would like to direct them to the tracker … -
What are the downsides of default ordering by PK in Django?
Django models now support default ordering, via Meta.ordering. What are the downsides to putting ordering = ["pk"] on my base model? In particular, I'm curious about the performance impact. The Django docs have a vague warning that this can hurt performance: Ordering is not free; each field to order by is an operation the database must perform. If a model has a default ordering (Meta.ordering) and you don’t need it, remove it on a QuerySet by calling order_by() with no parameters. But is ordering by the primary key actually expensive if I'm using Postgres as my database?