Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I share my PostgreSQL changes with teammates after git pull in a Django project?
I'm working on the backend of a web application using Django.Each developer has a local setup of the project, and we all pull updates from GitHub using git pull. I have a question about database changes: Whenever I make changes to the PostgreSQL database (for example, updating schema, adding new tables or data), is there a way for my teammates to automatically get those changes after they run git pull or for now use sqlite and after the project done deploy it on postgres? for my own i used sqlite but in this project i dont know it is a good idea or not -
Velvet: Static Files are searched by path string in urls
This issue refers to Velvet - Django Bootstrap 5 Premium Admin & Dashboard Template If you add a new URL urlpatterns = [ path( "dashboard/", views.velvet_dashboard, name="dashboard" ), # this finds Not Found: /dashboard/static/assets/libs/bootstrap/css/bootstrap.rtl.min.css path( "", views.velvet_dashboard, name="dashboard" ), # this finds Not Found: /static/assets/libs/bootstrap/css/bootstrap.rtl.min.css ] You can test it if you choose the Directions: RTL. logs for http://localhost:8000/: INFO 2025-10-16 08:24:43,331 basehttp 901281 124358292928064 "GET /static/assets/libs/bootstrap/css/bootstrap.rtl.min.css HTTP/1.1" 200 232911 logs for http://localhost:8000/dashboard/: WARNING 2025-10-16 08:34:37,514 log 902757 140627449730624 Not Found: /dashboard/static/assets/libs/bootstrap/css/bootstrap.rtl.min.css WARNING 2025-10-16 08:34:37,515 basehttp 902757 140627449730624 "GET /dashboard/static/assets/libs/bootstrap/css/bootstrap.rtl.min.css HTTP/1.1" 404 429 -
Which most web backend stack is common for remote Europe jobs. (python django or c# dotnet)? [closed]
Which most web backend stack is common for remote Europe jobs. (python django or c# dotnet) ? To choose which one to learn .......i am trying to find a a stack that has the most common jobs remotely si i can have a higher chance . -
Django: User Experience for checking if a person already exists in the database (first and last name, and birthday)
[I'm sure my use case has been addressed somewhere, but I'm not finding it.] In this use case, the user is registering a new person with the following fields: first name, last name, and birthday. If these are the same as an existing entry, the flow is to ask the user if any of the existing entries are the same. If yes, reject the entry. If no, add the entry. I'm looking for suggestions how to implement this. I know how to check for similar entries. What I'm not sure of is how to ask the "is this a duplicate of any of these other people" question to the user and then process the answer. Here's what I expect the flow is, and I wonder if there's a better way to do this. During clean() on the person entry form, we can query for similar entries (e.g. Jon Smith born 1/1/2000 and John Smith born 1/1/2000) and note there are some (or not). In is_valid(), if there is possible duplication, the system this would redirect to a view to list the possible duplicates and ask the question in a second form. And then if the user says it's a duplicate … -
How to prevent database overload with BlacklistedToken and OutstandingToken models in Django using Simple JWT?
'm working on a Django project using Simple JWT , and I've noticed that every time a user logs in, the generated tokens are stored in the BlacklistedToken and OutstandingToken tables in the database. As more users authenticate and new tokens are generated, these tables continue to grow, which could lead to database overload over time. What I want to achieve is to avoid these tables filling up unnecessarily with tokens, as I don't want to use a cron job to manually clean the tables or manage the tokens. What best practices exist for handling this situation? Is there a way to prevent these tokens from being stored persistently or to have them automatically cleaned up without using cron jobs? I would appreciate any suggestions to improve performance and keep the database optimized. I use postgresql for database. I have tried to set a script that runs every month but the table still fills up too much because the users are concurrent. -
Where should I put Django pre-flight checks that access the database?
I have a Django app that requires certain items to be in the database before it will run. I'd like to add checks at start time that will fail if these items are not found in the database. Is there a way to integrate these checks into the Django system check framework? I've played with this but I'm not sure if this is appropriate where the check makes database queries. And if this isn't the right place, is there a better way? I only need these checks to run once, before or at startup time. -
How to reset password in a Django UserChangeForm
I have a basic CustomUser model in my project. When I want to update it I fill my form with instance where I try to make user's passsword null, but anyway in the form i recieve: "No password set. Set password Raw passwords are not stored, so there is no way to see the user’s password." And Set password is a link that leads me to nowhere. I just want a password field to be null in my update form. views.py ... class CustomUserUpdateView(View): def get(self, request, *args, **kwargs): user_id = kwargs["user_id"] if request.user.is_authenticated: user = get_object_or_404(CustomUser, id=user_id) user.password = None if request.user == user: form = CustomUserChangeForm(instance=user) return render( request, "users/update.html", {"form": form, "user_id": user_id} ) else: return HttpResponse("you damn wrong") else: return HttpResponse("you idiot") def post(self, request, *args, **kwargs): user_id = kwargs["user_id"] user = get_object_or_404(CustomUser, id=user_id) form = CustomUserChangeForm(request.POST, instance=user) if form.is_valid(): form.save() return redirect("users_list") return render( request, "users/update.html", {"form": form, "user_id": user_id} ) ... models.py from django.contrib.auth.models import AbstractUser # Create your models here. class CustomUser(AbstractUser): pass def __str__(self): return self.username forms.py ... class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('first_name', 'last_name', 'username', 'password') update.html {% extends "base.html" %} {% block content %} {% if … -
More than basic form validation with Django
I'm learning Django with a small app allowing people to book houses for lodging. I have two models, describing a house and a booking (I'm currently working without a "Customer" model): # models.py from django.db import models class Housing(models.Model): name = models.CharField(max_length=255) capacity = models.SmallIntegerField() class Booking(models.Model): house = models.ForeignKey(Housing, on_delete=models.CASCADE) arrival_date = models.DateField(auto_now_add=False) departure_date = models.DateField(auto_now_add=False) client_id = models.TextField() nb_travellers = models.SmallIntegerField() I also have a ModelForm matching the Booking model, in which a customer can book a house: # forms.py from django.forms import ModelForm from .models import Booking class BookingForm(ModelForm): """Form to make a booking""" class Meta: model = Booking fields = "__all__" In my view, I retrieve the form data, and I'd like to add some validation before adding the new booking instance to the database: arrival_date must be before departure_date The number of travellers must not be higher then the houe capacity There must not be an existing booking in the databse which has overlapping dates with the new booking I already have code to compute those, it works in additional testing scripts I made, but I am struggling to integrate it properly in the view. Should I look deeper in Django forms validation documentation ? … -
Changing the owner of .venv created by uv inside Docker
I have a Django app build by uv running inside Docker. I mount the local filesystem as a volume in the container using Docker Compose so that edits to the source code locally trigger reloading of the app in the container. It almost works. The issue is that the .venv directory built by uv is owned by the root user of the Docker container. This means that I cannot edit those files from my local filesystem without root access. I have gotten around this with pip/pipenv/poetry/pdm in the past by installing the venv as a non-root user who has the same uid and guid as my local user (those values are passed into Docker via a .env file). But I can't work out how to do that for uv. Dockerfile: FROM python:3.12-slim-trixie # create non-root user RUN addgroup --system app && adduser --system --group app # set work directory WORKDIR /app # environment variables ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ UV_LINK_MODE=copy \ UV_PYTHON_DOWNLOADS=never \ UV_PROJECT_ENVIRONMENT=$APP_HOME/.venv # install uv COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/ # install system dependencies RUN apt-get update RUN apt-get install -y --no-install-recommends \ build-essential netcat-traditional \ python-is-python3 python3-gdal python3-psycopg2 # switch to app user [THIS MAKES THE NEXT … -
Error: TypeError: 'coroutine' object is not subscriptable
Code: total_deposit = transaction.filter(type='deposit').aaggregate(total=Sum('amount'))['total'] or 0 total_transfer = transaction.filter(type='transfer').aaggregate(total=Sum('amount'))['total'] or 0 Error: total_deposit = transaction.filter(type='deposit').aaggregate(total=Sum('amount'))['total'] or 0 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ How do i fix this?? -
Django email not sending — no error, but messages don’t arrive (using Gmail SMTP)
I’m trying to send emails from my Django project using Gmail’s SMTP server. The server runs without any errors, and my code executes successfully, but the emails never reach the recipient — not even in the spam folder. I’ve enabled 2-Step Verification on my Gmail account and generated an App Password specifically for this project, but it still doesn’t work. I want to understand why Django thinks the email was sent but it never actually arrives. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 465 EMAIL_USE_SSL = True EMAIL_HOST_USER = 'mygmail@gmail.com' EMAIL_HOST_PASSWORD = 'my-16-digit-app-password' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER i the Expected result was Recipient receives the email. but the actual result is Email never arrives, and no errors are raised. -
django getting 530, 5.7.0 Authentication Required despite using google's App Paswords
Have 2fa on Google, created the password, putting in the correct email and app password in the settings.py, yet still get Authentication Error. Tried both 587(TLS=True) and 465(SSL=True) but didn't seem to change anything. settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 465 EMAIL_USE_TLS = False EMAIL_USE_SSL = True EMAIL_HOST_USER = 'mygmail@gmail.com' EMAIL_PASSWORD = "my16digitpassword" DEFAULT_FROM_EMAIL = 'mygmail@gmail.com' What might be the problem/solution? Any answers for this problem feature "use google app password". -
How can I properly implement ManifestStaticFilesStorage in Django?
I'm attempting to implement ManifestStaticFilesStorage in my Django project. From what I've seen, this should be simple, but it's not behaving in the way I expect. Firstly, I have DEBUG=os.getenv("DEBUG", "False").lower() == "true" In my settings.py file, with DEBUG in my .env file set to "False". Next, I have the following settings for my static files: STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' MAX_DOCUMENT_FILE_SIZE_MB = 50 STATIC_URL = '/static/' if LOCAL: # LOCAL is False here STATIC_ROOT = os.path.join(BASE_DIR, 'static_collected') else: STATIC_ROOT = os.getenv('STATIC_ROOT') Finally, for my own sanity, I have some print statements at the end of my settings file that output when I run collectstatic, which output: STATICFILES_STORAGE: django.contrib.staticfiles.storage.ManifestStaticFilesStorage STATIC_ROOT: /var/www/html/static STATIC_URL: /static/ I have an nginx server set to serve static files at the above STATIC_ROOT. Finally, in my project's venv, I run python manage.py collectstatic And it copies the files successfully to the output directory I specified. The nginx server correctly serves them. However, after all this, the filenames remain their basic iterations, rather than including a hash as I expect. I'm using Django's {% static %} template in all my template HTML files. I've tried deleting the entire static folder and re-running collectstatic, but it outputs the same thing … -
How to aggregate a group by queryset in django?
I'm working with time series data which are represented using this model: class Price: timestamp = models.IntegerField() price = models.FloatField() Assuming timestamp has 1 min interval data, this is how I would resample it to 1 hr: queryset = ( Price.objects.annotate(timestamp_agg=Floor(F('timestamp') / 3600)) .values('timestamp_agg') .annotate( timestamp=Min('timestamp'), high=Max('price'), ) .values('timestamp', 'high') .order_by('timestamp') ) which runs the following sql under the hood: select min(timestamp) timestamp, max(price) high from core_price group by floor((timestamp / 3600)) order by timestamp Now I want to calculate a 4 hr moving average, usually calculated in the following way: select *, avg(high) over (order by timestamp rows between 4 preceding and current row) ma from (select min(timestamp) timestamp, max(price) high from core_price group by floor((timestamp / 3600)) order by timestamp) or Window(expression=Avg('price'), frame=RowRange(start=-4, end=0)) How to apply the window aggregation above to the first query? Obviously I can't do something like this since the first query is already an aggregation: >>> queryset.annotate(ma=Window(expression=Avg('high'), frame=RowRange(start=-4, end=0))) django.core.exceptions.FieldError: Cannot compute Avg('high'): 'high' is an aggregate -
How to search by multiple fields on django_opensearch_dsl
I have an opensearch server in which I want to search items and apply some filters to the search: search = Item.search().query("match", name="test") I need to search items by multiple filters, like name, date, location, etc. For this I will need some other kind of queries like "range" or "terms". Now the issue is I've trying using opensearch-dsl package like this: search_1 = ESQ("match", name="test") search_2 = ESQ("terms", name="location") search_3 = ESQ("range", name="date") filters = [search_1, search_2, search_3] query = ESQ("bool", should=filters) search = FreezerItemDocument.search().query(query) This is not working, constantly returning errors like: {"error":"unhashable type: 'Bool'"} Event if I try to run the query individually like this: query = ESQ("match", name="test") search = FreezerItemDocument.search().query(query) How can I do a search by multiple fields? -
Why does pytest fail to resolve Related model references in a Django package?
I have an installable Django package that I have built and was starting to write tests for it. I am using pytest-django. However, when I run the tests, almost all the tests fail and I keep getting this error:- request = <SubRequest 'django_db_setup' for <Function test_filter_with_full_name>>, django_test_environment = None django_db_blocker = <pytest_django.plugin.DjangoDbBlocker object at 0x10072ba40>, django_db_use_migrations = False, django_db_keepdb = True django_db_createdb = False, django_db_modify_db_settings = None @pytest.fixture(scope="session") def django_db_setup( request: pytest.FixtureRequest, django_test_environment: None, django_db_blocker: DjangoDbBlocker, django_db_use_migrations: bool, django_db_keepdb: bool, django_db_createdb: bool, django_db_modify_db_settings: None, ) -> Generator[None, None, None]: """Top level fixture to ensure test databases are available""" from django.test.utils import setup_databases, teardown_databases setup_databases_args = {} if not django_db_use_migrations: _disable_migrations() if django_db_keepdb and not django_db_createdb: setup_databases_args["keepdb"] = True aliases, serialized_aliases = _get_databases_for_setup(request.session.items) with django_db_blocker.unblock(): > db_cfg = setup_databases( verbosity=request.config.option.verbose, interactive=False, aliases=aliases, serialized_aliases=serialized_aliases, **setup_databases_args, ) .venv/lib/python3.12/site-packages/pytest_django/fixtures.py:198: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
How to integrate OpenAI GPT API in Django REST Framework project?
I’m building a Django REST Framework (DRF) project and I want to integrate OpenAI GPT API to provide AI-powered responses to users. I’ve tried setting up the API call using Python’s requests library and also with the official openai Python package, but I’m running into issues with authentication and response handling. Here’s my current code snippet: import openai openai.api_key = "YOUR_API_KEY" response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Hello, can you help me with Django?"} ] ) print(response['choices'][0]['message']['content']) Problem: Sometimes I get an authentication error: "Invalid API key" Other times the API call works but I’m not sure how to integrate it properly into a DRF view so that it returns a JSON response to the frontend. What I want: A clear way to call OpenAI GPT from a Django REST API endpoint Return the GPT response in JSON format to a React frontend What I’ve tried: Adding API key in .env and using os.environ Testing with curl — works sometimes Wrapping the call inside a DRF APIView — but facing serialization issues Any advice or working example would be highly appreciated 🙏 I tried calling the OpenAI GPT API inside … -
Django runserver returns ERR_CONNECTION_RESET on Windows 11 (no errors in terminal)
I’m learning Django and trying to run my project locally on Windows 11. When I start the server, it runs without any errors, but when I try to open it in my browser (127.0.0.1:8000 or 127.0.0.1:8001), I get this message: Hmmm… can’t reach this page ERR_CONNECTION_RESET What I’ve Tried Running python manage.py runserver 0.0.0.0:8001 Running from both PowerShell and Command Prompt Confirmed I’m using a virtual environment (venv) inside my project folder Checked that my firewall allows Python Reinstalled Django and Python Verified no errors show in the terminal Terminal output: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Django version 5.2.5, using settings 'StudentERP.settings' Starting development server at http://0.0.0.0:8001/ Quit the server with CTRL-BREAK. WARNING: This is a development server. Do not use it in a production setting. [27/Aug/2025 14:57:56,986] - Broken pipe from ('127.0.0.1', 23878) [27/Aug/2025 14:57:57,167] - Broken pipe from ('127.0.0.1', 23879) What I Expected I expected to see Django’s default “Congratulations!” page at http://127.0.0.1:8001/. My Setup Windows 11 Home, Version 23H2 (Build 22631) Python 3.11.9 (64-bit) installed from python.org Django 5.2.5 Running inside VS Code PowerShell terminal Personal laptop (not managed by any organization) Question Why am I … -
How to authenticate requests with django allauth (headless)
I am always getting a 401 response after login to django-allauth on session (and other endpoints). See example code: def login(email, password): response = requests.post( f'{baseurl}/api/allauth/app/v1/auth/login', headers={ 'accept': 'application/json', 'Content-Type': 'application/json', }, json={ 'password': password, 'email': email } ) return response def get_session(session_token): response = requests.get( f'{baseurl}/api/allauth/app/v1/auth/session', headers={ 'accept': 'application/json', 'Content-Type': 'application/json', 'X-Session-Token': session_token, } ) return response login_response = login(email, password) print(f"Status Code: {login_response.status_code}") #print(f"Response: {json.dumps(login_response.json(), indent=2)}") session_token = login_response.json()["meta"]["session_token"] print("Session_token=",session_token) session_response = get_session(session_token) print(f"Status Code: {session_response.status_code}") print(f"Response: {json.dumps(session_response.json(), indent=2)}") Here is the output I am getting: Status Code: 200 Session_token= 165aj7jqqq165drt6nbg8wo5dcf9ncch Status Code: 401 Response: { "status": 401, "data": { "flows": [ { "id": "login" }, { "id": "signup" }, { "id": "password_reset_by_code", "is_pending": false } ] }, "meta": { "is_authenticated": false } } So login works fine, but then calling other allauth headless endpoints always lead to 401 response. Calling other DRF endpoints protected by permission_classes = [permissions.IsAuthenticated] works just fine too. Here are my important settings... INSTALLED_APPS = [ ... "allauth", "allauth.account", "allauth.headless", #'allauth.socialaccount', # "allauth.mfa", "allauth.usersessions", "oauth2_provider", ... "rest_framework", ... ] AUTHENTICATION_BACKENDS = ( # Django "django.contrib.auth.backends.ModelBackend", # allauth "allauth.account.auth_backends.AuthenticationBackend", # oauth2 "oauth2_provider.backends.OAuth2Backend", ) REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "allauth.headless.contrib.rest_framework.authentication.XSessionTokenAuthentication", "oauth2_provider.contrib.rest_framework.OAuth2Authentication", # oauth2 "rest_framework.authentication.SessionAuthentication", "rest_framework.authentication.BasicAuthentication", … -
Highlight affected lung regions in chest X-rays using Python, Django, and CNN in a web-based pneumonia detection app
Our team is building a web-based pneumonia detection system using Python, Django, and a CNN. The model classifies chest X-rays as pneumonia or normal, but we now want to highlight affected lung regions for healthcare workers. Challenges: Generating heatmaps/saliency maps (e.g., Grad-CAM). Efficiently preprocessing images in Django. Integrating predictions + highlights into the frontend. Handling low-quality/noisy images. Keeping the pipeline fast, maintainable, and user-friendly. How can we structure the end-to-end pipeline to show interpretable visualizations alongside predictions? Any best practices, libraries, or design patterns for CNN-based pneumonia detection apps that highlight affected areas in real-time? We have successfully trained a CNN model that classifies pneumonia with good accuracy and integrated basic image uploads in Django. We tried generating simple Grad-CAM heatmaps in Python, but we’re unsure how to connect these visualizations efficiently to Django views while handling real-time predictions. We expect a seamless workflow where users can upload X-rays and see both classification and highlighted areas immediately, but current attempts are slow or messy. -
Usage of Django
I know this question will sound silly but how exactly is django used in production servers, like is it used mostly with rest_framework for creating APIs or is it just used as a full-stack framework with template rendering. Asking because templates in prod seems not right. Want to know the general case of usage of Django -
Why does my Django model’s save() method run twice when creating an object in the admin panel?
I have a Django model with a custom save() method: class MyModel(models.Model): name = models.CharField(max_length=100) def save(self, *args, **kwargs): print('Saving...') super().save(*args, **kwargs) When I create a new object through the Django admin, I see "Saving..." printed twice in the console. -
How to configure an enterprise Django project with type safety, AI agents, and built-in support system?
I’m working on a large-scale Django project for enterprise use and facing challenges related to: Reliable type safety for settings and configuration (preferably using Pydantic) Combining core business features (user management, support/ticketing, CRM, reporting, and AI agents) without manually integrating and customizing a dozen third-party apps Fast production setup, including multi-database, Docker deployment, automated client generation, and background tasks With the traditional settings.py approach, keeping everything maintainable and scalable is tough—lots of boilerplate, validation issues, and manual integration steps that slow down development. Are there any open-source Django frameworks or libraries that provide these features out-of-the-box, with type safety and ready integration for enterprise-scale deployment? I recently started developing django-cfg (docs), which aims to address these exact pain points by providing Pydantic-based configuration, built-in enterprise apps, and automated tooling. I’m interested in community feedback, suggestions for best practices, or alternative solutions that others have used for similar requirements. -
VS Code Multi line Selection problem in version code_1.104.3-1759409451_amd64
how do i resolve this error in VS code_1.104.3-1759409451_amd64 , when you click down mouse to select a line of code, or block of code, its like it select s each of the character and turns the whole ide gibberish you cant even see what you selected, i have disabled Column Select Mode Clicking and dragging to select text or code causes severe visual corruption, making the entire interface flicker and the selection impossible to see. -
How to handle simultaneous data from multiple ESP32 devices without mixing data in Django + DRF?
I’m working on my thesis and building a Django web application that receives height, weight, and temperature data from multiple ESP32 devices. Each ESP32 has a unique device_id and sends all three measurements to my Django backend using Django REST Framework (via HTTP POST with JSON). The issue happens when two ESP32 devices send data at the same time. The backend sometimes mixes their data, with measurements from one device overwriting or merging with another’s entry in the cache. Question: What’s the best way to handle simultaneous data submissions from multiple devices in Django + DRF, ensuring each device’s data stays separate and accurate? i tried to make the web app scan available devices or online esp32 devices, now the problem is whenever the esp32 sends data saying that it is available, it stack showing multiple devices in the selection.