Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
why my EC2 instance is not recognizing my app?
im new in AWS and i tried migrating my files in EC2 and i see this error, is it a problem in my structure? I would really appreciate any help since im working in my portfolio and i cant seem to host it correctly :( my repo: "https://github.com/theowla/Portfolio_TW.git" (venv) ubuntu@ip-172-31-37-85:~/Portfolio_TW/portfolio$ python manage.py migrate Traceback (most recent call last): File "/home/ubuntu/Portfolio_TW/portfolio/manage.py", line 22, in <module> main() File "/home/ubuntu/Portfolio_TW/portfolio/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ubuntu/Portfolio_TW/venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line utility.execute() File "/home/ubuntu/Portfolio_TW/venv/lib/python3.12/site-packages/django/core/management/__init__.py", line 416, in execute django.setup() File "/home/ubuntu/Portfolio_TW/venv/lib/python3.12/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ubuntu/Portfolio_TW/venv/lib/python3.12/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) ^^^^^^^^^^^^^^^^^^^^^^^ File "/home/ubuntu/Portfolio_TW/venv/lib/python3.12/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/usr/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1324, in _find_and_load_unlocked ModuleNotFoundError: No module named 'project' i tried migrating my files after i changed the folder name and it now doesnt find my app -
Django DRF, Cannot reproduce POST request using APIClient and APITestCase, payload fields are removed
I have the following setup in Django DRF: class TagSerializer(serializers.Serializer): id = serializers.UUIDField(read_only=True) name = serializers.CharField(required=True) style = serializers.JSONField(read_only=True) class TagCreationMixin: def create(self, validated_data): tags = validated_data.pop("tags", []) failure_mode = self.Meta.model.objects.create(**validated_data) for tag in tags: current_tag, _ = models.Tag.objects.get_or_create(**tag) failure_mode.tags.add(current_tag) return failure_mode class ItemSerializer(TagCreationMixin, serializers.ModelSerializer): tags = TagSerializer(many=True, required=False) class Meta: model = models.Item fields = "__all__" And I want to automatize tests using APIClient and APITestCase. I have the following test defined: class TestAPIMissingTags(APITestCase): fixtures = [ "core/fixtures/users.yaml" ] payload = { "name": "test", "tags": [{"name": "test"}, {"name": "critical"}], } def setUp(self): self.user = models.CustomUser.objects.get(username="jlandercy") self.client = APIClient() self.client.force_authenticate(user=self.user) def test_complete_payload_is_sent(self): response = self.client.post("/api/core/item/", data=self.payload) print(response) print(response.json()) Which returns a 201 but without any tags, it seems they are popped from the initial payload: <Response status_code=201, "application/json"> {'id': 'f3cd6bbb-239f-4f47-9b2d-f648ead76bdd', 'tags': [], 'name': 'test'} Anyway when I challenge Swagger with the same endoint and payload it works as expected: { "id": "6d05c2e3-fce3-420d-bef9-4bccd28062f7", "tags": [ { "id": "fa70c875-818b-4ca2-9417-4209fd377453", "name": "test", "style": { "background-color": "#cc7a13" } }, { "id": "9fd59657-4242-432f-b165-1ed0a67546e3", "name": "critical", "style": { "background-color": "#bf8100" } } ], "name": "test" } Why cannot I reproduce the same behavior than Swagger using the APIClient. -
VS Code python extension seeing some not all Django class
Simple problem: the Python extension of VS Code is not seeing a Django class, while all other classes in same file are presented. Restarting, disabling/enabling, switch to pre-release for the extension doesn't change anything. Confirmed it was the extension as disabling it removes all import objects. AdminUserCreationForm is not being detected while UserCreationForm and other classes are visible. If I visit the source file by CTRL+click I can clearly see the class there: I've tried clearing a few VS Code caches (under AppData\Roaming\Code) to no avail. -
Django DRF, create an Item with associated tags whether they exist or not
I have the following create function for ItemSerializer class. It aims to create new Item with tags, creating tags on the fly if they does not exist or getting them if they exist. def create(self, validated_data): tags = validated_data.pop("tags", []) item= models.Item.objects.create(**validated_data) for tag in tags: current_tag, success = models.Tag.objects.get_or_create(**tag) item.tags.add(current_tag) return item Anyway when I perform a POST on the Item with already existing tag: { "tags": [{"name": "My Tag"}], "name": "My Item" } I get the following DRF 400 answer: { "tags": [ { "name": [ "tag with this name already exists." ] } ] } It seems in this case my create function is skipped and Django DRF tries to create the tag anyway. -
Django manage command set stdout and stderr
Is there a way to set stdout and stderr from base_stealth_options in BaseCommand when running the django command? I can't find any documentation about how to use those options. For example, I would like to set stdout and stderr to a logger info and error when running python manage.py foo. Code reference: https://github.com/django/django/blob/stable/5.2.x/django/core/management/base.py#L269 This is my attempt at making my own manage_custom_logging.py. I am wondering if there is a better way to do this since base_stealth_options exists. # manage_custom_logging.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys import traceback import logging logger = logging.getLogger('manage_custom_logging') class StreamToLogger(object): def __init__(self, logfct): self.logfct = logfct def write(self, buf): for line in buf.rstrip().splitlines(): self.logfct(line.rstrip()) def flush(self): pass def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_django_app.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " 'available on your PYTHONPATH environment variable? Did you ' 'forget to activate a virtual environment?' ) from exc try: sys.stdout = StreamToLogger(logging.info) sys.stderr = StreamToLogger(logging.error) execute_from_command_line(sys.argv) except Exception: logger.error(traceback.format_exc()) if __name__ == '__main__': main() -
Where to set up subdomain routing? Front-end (React) or Django (Backend)?
I'm currently building a multi-tenant web application using Django and React. Right now, each user's page is available at a URL like https://mywebsite.com/. However, I want to change this so that each user has their own subdomain, for example: https://.mywebsite.com. My setup is as follows: I'm using React for the frontend and Django (with Django REST Framework) for the backend. Both are running on the same server. I’m serving the React build/ folder directly through Django by connecting it in the Django urls.py file. What I want to achieve is true subdomain-based routing so that each user or tenant can have their own subdomain. I’m not sure exactly what changes are needed to make this work, especially across the different layers of the stack. Specifically, I’m looking to understand what needs to be done at the DNS or Nginx/server configuration level, what changes I need to make in Django to detect and handle subdomains, and whether any updates are needed on the React side. I’m also wondering whether there’s a way to test this kind of subdomain setup locally during development (like on localhost). Finally, I'd like to know how to extract the subdomain (which would be the username or … -
My VM not connecting to MySQL – 2002 error
I’m currently experiencing issues with my virtual machine named "monitoramentoati". When trying to access my application through the domain https://monitoramentoati.camf.org.br/admin/login/, I encounter the following error from Django: "OperationalError at /admin/login/ (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111)")" The full traceback points to an issue with the Django application being unable to connect to the local MySQL server via socket. However, when I check the MariaDB service inside the VM, it shows as active (running) and the socket being used is: "/run/mysqld/mysqld.sock" This differs from the path Django is trying to use (/var/run/mysqld/mysqld.sock), which may indicate a misconfiguration or a linking issue in the filesystem. Additionally, I’m seeing logs like the following in the system log viewer (Cloud Logging): "May 14 15:43:56 monitoramento-ati gunicorn[915]: django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111)")" I was wondering if you could help me with this problem. What should I do? I tried to update the mysql, django and everything that I can and did't work. -
Creating TabularInline in Django Admin View for inherited Many2Many relation
I have a Tag Model and Mixin that is used for adding tags to entities whenever it is needed. class Tag(models.Model): name = models.CharField(max_length=64, unique=True) class TagMixin(models.Model): class Meta: abstract = True tags = models.ManyToManyField(Tag, blank=True) To create new entities it works well, it implicitly creates the correspondence table for the many to many relation: class Item(TagMixin): name = models.CharField(max_length=64) But what if I want create an admin view on Item where tag is a TabularInline input ? How should I fill the configuration: class ItemTagInline(admin.TabularInline): model = ? @admin.register(models.Item) class ItemAdmin(admin.ModelAdmin): list_display = ("id", "name") inlines = [ItemTagInline] -
Airwallex Payment Link not redirecting to custom redirect_url after successful payment
I'm integrating Airwallex payment links into my web application. After a successful payment, instead of being redirected to my custom success URL (e.g., https://example.com/paymentsuccess), users are taken to the Airwallex default success page. Here's how I'm creating the payment link What I've Checked: The URLs are correct and publicly accessible. There are no obvious network or HTTPS issues. I confirmed that the payment completes successfully — it’s just the redirection that fails. Tech Stack: Backend: Python/Django Airwallex SDK/API Environment: Test mode What I'm Looking For: Is there any additional setting or flag required when creating the Airwallex payment link to enforce redirection? Does Airwallex override redirect_url in certain scenarios? Is there a webhook/setting in the dashboard I need to configure? -
NEAR API python
getting error when setting up py-near for a django project getting error when downloading py-near using pip AttributeError: module 'configparser' has no attribute 'SafeConfigParser'. Did you mean: 'RawConfigParser'? pip install py-near -
What is the best and production-safe way to handle long process them efficiently in Django, ideally with parallel processing?
I'm working on a Django app where users upload large .txt files that need to be parsed and stored in a PostgreSQL database. The files can contain hundreds of thousands of lines, and processing them can take a long time. Currently, I'm using threading.Thread with an in-memory tasks_registry to process the file and stream task status. It works in development, but I now realize this approach is not safe in production, especially with Gunicorn and multiple workers. upload data / Process the file in parallel for better performance Send a response to the frontend after the upload completes, while the processing continues in the background Safely handle this under Gunicorn or another WSGI server Any recommendations for architecture or proven patterns would be very helpful? -
Getting this error had repository from git and python virtual environment is activated just getting problem to activate from source env/bin/activate
WARNINGS: ?: (staticfiles.W004) The directory 'C:\Ansh\ecom\django_project_boilerplate\static_files' in the STATICFILES_DIRS setting does not exist. System check identified 1 issue (0 silenced). You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): auth. Run 'python manage.py migrate' to apply them. May 15, 2025 - 23:00:06 Django version 5.2.1, using settings 'demo.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. WARNING: This is a development server. Do not use it in a production setting. Use a production WSGI or ASGI server instead. For more information on production servers see: https://docs.djangoproject.com/en/5.2/howto/deployment/ getting this error