Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
{"status":"error","message":"An unexpected error occurred","errors":"[Errno 5] Input/output error"}
This problem occurs when I create an order in my project. I hosted it on GoDaddy, and the problem occurred only after hosting. If I run this locally, it will create the order. Understand this error Error saving data: dl {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …} this is the error it shows in the react front end {"status":"error","message":"An unexpected error occurred. "errors": "Input/output error"} and this is the error shows in the flutter app while creating the order -
How can I set up filtering in the form model of one field based on another when selecting?
I have 2 model tables. In the first table I have a form in the set in which there is one interesting field. This field can have the same values. If we consider the second table model - then in the second table model I placed 2 fields from the first table. And in these two fields - there is a field in which there can be duplicate values. I would like, if possible, to enter data into the second table - taking into account: selection of data from the city field and most importantly - so that after selecting in the city field - some filtering of the second field occurs. For example, filtering of two fields occurs according to the selected first field and is substituted into the second field. How can this be done. I select the city field - and so that the second field is filtered. How can I set up filtering in the form model of one field based on another when selecting? Help me please, I will be glad to any hint on how to do this? from django.db import models # Create your models here. TYPE_OBJECT = [ ("1", "Котельная"), ("2", "Сети"), … -
Production server Bad Request (Error: ValueError: Unknown endpoint type: 'fd')
This morning, my production website went down with a "Bad Request" error. It was working the day before, and I made no changes that might have caused the error. Below is the traceback I got in the asgi.log file. I can provide more information if needed, but not sure what. I have tried the following: Uninstalled all from requirements.txt, then reinstalled, and restarted the server Added '*' to ALLOWED_HOSTS, and set DEBUG=True, but this did not work, so I undid those changes. Rebooted the server The site works fine in my local machine, whether I use DEBUG = FALSE or DEBUG = True. Traceback (most recent call last): File "/home/raphaeluziel/raphi/venv/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/raphaeluziel/raphi/venv/lib/python3.12/site-packages/daphne/cli.py", line 171, in entrypoint cls().run(sys.argv[1:]) File "/home/raphaeluziel/raphi/venv/lib/python3.12/site-packages/daphne/cli.py", line 291, in run self.server.run() File "/home/raphaeluziel/raphi/venv/lib/python3.12/site-packages/daphne/server.py", line 130, in run ep = serverFromString(reactor, str(socket_description)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/raphaeluziel/raphi/venv/lib/python3.12/site-packages/twisted/internet/endpoints.py", line 1874, in serverFromString nameOrPlugin, args, kw = _parseServer(description, None) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/raphaeluziel/raphi/venv/lib/python3.12/site-packages/twisted/internet/endpoints.py", line 1794, in _parseServer plugin = _matchPluginToPrefix( ^^^^^^^^^^^^^^^^^^^^^ File "/home/raphaeluziel/raphi/venv/lib/python3.12/site-packages/twisted/internet/endpoints.py", line 1809, in _matchPluginToPrefix raise ValueError(f"Unknown endpoint type: '{endpointType}'") ValueError: Unknown endpoint type: 'fd' Traceback (most recent call last): File "/home/raphaeluziel/raphi/venv/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/raphaeluziel/raphi/venv/lib/python3.12/site-packages/daphne/cli.py", line 171, in entrypoint cls().run(sys.argv[1:]) … -
How can I configure the wrapping of a large long line of text in a form Django?
I have a form with OneToOneField where data is loaded from another table model. But I often have large data sizes there and the displayed text does not fit into the window size. Is it possible to somehow configure the text wrapping to 2-3 lines? How can I configure the wrapping of a large long line of text in a form? from django.db import models # Create your models here. class ArkiObject (models.Model): nameobject = models.TextField(verbose_name="Наименование объекта") def __str__(self): return self.nameobject TYPE_OBJECT = [ ("1", "Котельная"), ("2", "Сети"), ("3", "БМК"), ("4", "ЦТП"), ("5", "ТГУ"), ] TYPE_WORK = [ ("1", "Реконструкция"), ("2", "Капитальный ремонт"), ("3", "Строительство"), ] TYPE_CITY = [ ("1", "Бронницы"), ("2", "Луховицы"), ("3", "Павловский Посад"), ("4", "Раменское"), ("5", "Шатура"), ] class ArkiOneObject (models.Model): city = models.CharField( choices=TYPE_CITY, verbose_name="Выберите ОМСУ") typeobject = models.CharField( choices=TYPE_OBJECT, verbose_name="Выберите тип объекта") typework = models.CharField( choices=TYPE_WORK, verbose_name="Выберите тип работ") nameobject = models.OneToOneField(ArkiObject, verbose_name="Наименование объекта", on_delete=models.CASCADE) from django import forms from .models import * class FormOne (forms.ModelForm): class Meta: model = ArkiOneObject fields = "__all__" class FormTwo (forms.ModelForm): class Meta: model = ArkiTwoObject fields = "__all__" class FormThree (forms.ModelForm): class Meta: model = ArkiObject fields = "__all__" <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>title</title> </head> … -
Setup to deploy different django app do different environment(Prod/UAT)
I'm building an application using Django for backend and React for frontend and there's need to deploy do different environments, UAT and PROD. How do I set up the Nginx and Django environments? Please share your views or resources that could be helpful. Recommendations on tools for building an industry pipeline is also welcome. Note: I'm still using raw IP -
Django URL matching but displaying 'Page Not Found'
I'm getting a page not found error for a url I know is defined in urls.py - exact same code works on the qa server, but for some reason on the live server it gives a 404 error. 404 error returned even though it says the url is matched! I put debug=True temporarily on the live server to get the list of urls. Going a little crazy here, any ideas? -
Django project -createsuperuser Doesnt work
I am facing an issue while creating my superuser using the following command: ./manage.py createsuperuser, it seems that there is no error but the line where í can set my email and password doesnt appear enter image description here Could someone kindly help me understand the root cause of this problem? If you need additional screenshots, please feel free to ask. Thank you for your assistance. Best regards, -
Password doesnt get saved from the signup request in django-allauth
I have a django app and i am using django-allauth to authenticate users.I dont have anything complex setup right now, all i am trying to do is let the user signup through email and password and verify their email before they can login. I am testing the apis through postman right now and when i hit the singup endpoint, everything works fine: the user object is saved in database with the relevant fields(email, phone number, role) but the password does not get saved and because of this i am not able to login or do anything else in the authentication process. This is my setup: I am using the headless apis rather than regular ones. This is my settings.py INSTALLED_APPS = [ .... 'allauth', 'allauth.account', 'allauth.headless', 'allauth.usersessions', ] AUTHENTICATION_BACKENDS = [ # `allauth` specific authentication methods, such as login by email 'allauth.account.auth_backends.AuthenticationBackend', # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend' ] #ALLAUTH SETTINGS ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True ACCOUNT_SIGNUP_FIELDS = [ 'email*', 'phone*', 'password*', ] ACCOUNT_SIGNUP_FORM_CLASS = "user_onboarding.forms.CustomSignupForm" ACCOUNT_ADAPTER = 'user_onboarding.adapter.CustomAccountAdapter' ACCOUNT_LOGIN_METHODS = {"email"} HEADLESS_ONLY = True HEADLESS_FRONTEND_URLS = { "account_confirm_email": "/account/verify-email/{key}", "account_reset_password": "/account/password/reset", "account_reset_password_from_key": "/account/password/reset/key/{key}", "account_signup": "/account/signup", "socialaccount_login_error": "/account/provider/callback", } ACCOUNT_PHONE_VERIFICATION_ENABLED = False … -
Django Multi-Database ValueError: "Cannot assign Role object: the current database router prevents this relation"
I'm encountering a ValueError in my Django application when trying to save a User object with a related UserRoleAssociation in the admin interface. The error occurs in a multi-database setup where both the UserRoleAssociation and Role models are intended to use the members database. The error message is: ValueError: Cannot assign "<Role: Role object (67c43a2e-c4e7-4846-bd31-700bf5d35e82)>": the current database router prevents this relation. I have a Django project with two databases: default and members. The User, UserRoleAssociation, and Role models are all configured to use the members database via admin classes. The error occurs when saving a User object with an inline UserRoleAssociation in the Django admin. Models # models.py class Role(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) role_name = models.CharField(max_length=255, unique=True) class Meta: db_table = "roles" class UserRoleAssociation(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE) role = models.ForeignKey("Role", on_delete=models.CASCADE) def __str__(self): return f"{self.role.role_name}" class Meta: unique_together = ["user", "role"] db_table = "user_role_association" class User(models.Model): phone_number = models.CharField(max_length=15) is_premium = models.BooleanField(default=False) roles = models.ManyToManyField("Role", through=UserRoleAssociation, related_name="users") class Meta: db_table = "users" app_label = "members" base_manager_name = 'objects' default_manager_name = 'objects' Admin Configuration I use a custom MultiDBModelAdmin and MultiDBTabularInline to enforce the members database: # admin.py class MultiDBModelAdmin(admin.ModelAdmin): using = "members" def save_model(self, request, obj, … -
How to access a Django site from another device on a local network
I'm running a Django site on my computer and I want to access it from another device on the same Wi-Fi network (for example, from a phone or another laptop). I tried running python manage.py runserver, but I can only access the site from the same computer using localhost. I don’t know how to make the site accessible from other devices. How can I properly configure Django and my computer so that the site is accessible from other devices? To be honest, when trying to find a solution, I found a couple of options where I needed to merge the project into different services, but that doesn't work for me. Thanks in advance! -
Создание профиля пользователя в Django при регистрации: где лучше размещать логику — во вьюхе или в форме? Плюсы, минусы и рекомендации для начинающих [closed]
asdasdadsdadadsadsorry for that question, guys пытаюсь скопировать стек оверфлоуasdasdadsdadadsadsorry for that question, guys пытаюсь скопировать стек оверфлоуasdasdadsdadadsadsorry for that question, guys пытаюсь скопировать стек оверфлоу -
Unable to find GDAL library in conda env
I have a django project configured with pycharm. I am using a conda env for packages installations. I have installed gdal. But when I run server, I see: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal310", "gdal309", "gdal308", "gdal307", "gdal306", "gdal305", "gdal304", "gdal303", "gdal302", "gdal301"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. I have added this at top of settings.py: import os os.environ['GDAL_LIBRARY_PATH'] = r'C:\Users\Admin.conda\envs\my-env\Library\bin\gdal.dll' I even added GDAL_LIBRARY_PATH globally as user variable, but I still see this error. How to get it working? -
Why is my selenium script blocked in production in headless mode, while it works completely fine in local enviroment? i use python
i have a selenium web scrapper, that runs well in my local development environment even in headless mode. However when i deploy it in production in a Linode Ubuntu VPS, somehow it fails with a Timeout exceeded message.Any help would be highly appreciated. I use django management commands to run the script, and it fetches data from a japanese car website. Here is the code import json from numbers import Number from pathlib import Path import traceback import asyncio import warnings import time import pandas as pd from inspect import Traceback import re from bs4 import BeautifulSoup from django.views.i18n import set_language from google_currency import convert from deep_translator import GoogleTranslator,LingueeTranslator import undetected_chromedriver as UC from selenium import webdriver from selenium.webdriver import DesiredCapabilities from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.select import Select from selenium_stealth import stealth from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import NoSuchElementException, TimeoutException, NoAlertPresentException from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import service from base_selenium_browser import BaseSeleniumBrowser from basebrowser import BaseBrowser from bs4 import BeautifulSoup import random from random import randint from bs4 import SoupStrainer from cleaning.cleaning_data import DataProcessor from saving_data.saving_data import SavingData from webdriver_manager.chrome import ChromeDriverManager BASE_PATH = Path(__file__).resolve().parent.parent class PriceFinderBot(BaseSeleniumBrowser): def __init__(self): self.__data_saver = … -
Shouldn't the call to django_stubs_ext.monkeypatch should be inside a TYPE_CHECKING check?
Simple question here about django_stubs_ext. Shouldn't the monkey patching occur only during TYPE_CHECKING ? Something like this: # settings.py if TYPE_CHECKING: import django_stubs_ext django_stubs_ext.monkeypatch() -
pythonanywhere getting an error when deploying
Something went wrong :-( Something went wrong while trying to load this site; please try again later. Debugging tips If this is your site, and you just reloaded it, then the problem might simply be that it hasn't loaded up yet. Try refreshing this page and see if this message disappears. If you keep getting this message, you should check your site's server and error logs for any messages. Error code: 502-backend your text I WAS TRYING TO DEPLOY A DJANGO PROJECT VIA PYTHONANYWHERE BUT I GET THIS ERROR Something went wrong :-( Something went wrong while trying to load this site; please try again later. Debugging tips If this is your site, and you just reloaded it, then the problem might simply be that it hasn't loaded up yet. Try refreshing this page and see if this message disappears. If you keep getting this message, you should check your site's server and error logs for any messages. Error code: 502-backend -
How do I structure a Django REST Framework API backend when the frontend is already built?
I'm building a Visitor Management System (VMS), and I've been given a complete frontend to work with. My task is to build the API-based backend using Django and Django REST Framework, which I'm familiar with from smaller projects. However, I'm struggling to organize the backend efficiently and expose the right endpoints that match what the frontend expects. Set up Django and Django REST Framework. Defined my models (e.g., VisitorPreRegistration, User). Started creating serializers and basic viewsets. My Questions: What is the best way to structure a Django API-only project, especially when the frontend is decoupled? Are there packages or patterns (like cookiecutter-django, DRF extensions, or project templates) that help speed up development and reduce boilerplate? How do I effectively map frontend forms and filters (e.g., visitor type, host search, arrival time) to backend endpoints? 🔍 What I tried: I’ve read the Django and DRF documentation, and tried watching a few YouTube tutorials, but most assume a monolithic approach or skip the API-only setup with an existing frontend. -
django-minify-html breaks Google Analytics injection
I'm running into an issue and would appreciate some pointers. I have a production Django app where I included Google Analytics using a context processor and conditionally render it in my base.html template like this: <!-- Google Analytics --> {% if GOOGLE_ANALYTICS_ID %} <script async src="https://www.googletagmanager.com/gtag/js?id={{ GOOGLE_ANALYTICS_ID }}"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', '{{ GOOGLE_ANALYTICS_ID }}'); </script> {% endif %} <!-- End Google Analytics --> Everything was working fine but the GA tracking completely breaks after enabling django_minify_html These are my current settings: For base.py: USE_MINIFICATION = DJANGO_ENV == "production" MINIFY_HTML = { "enabled": USE_MINIFICATION, "remove_comments": True, "minify_js": False, "minify_css": True, } For production.py from .base import MIDDLEWARE as BASE_MIDDLEWARE MIDDLEWARE = list(BASE_MIDDLEWARE) # Insert MinifyHtmlMiddleware after WhiteNoiseMiddleware try: whitenoise_index = MIDDLEWARE.index("whitenoise.middleware.WhiteNoiseMiddleware") MIDDLEWARE.insert(whitenoise_index + 1, "django_minify_html.middleware.MinifyHtmlMiddleware") except ValueError: try: security_index = MIDDLEWARE.index("django.middleware.security.SecurityMiddleware") MIDDLEWARE.insert(security_index + 1, "django_minify_html.middleware.MinifyHtmlMiddleware") except ValueError: MIDDLEWARE.insert(0, "django_minify_html.middleware.MinifyHtmlMiddleware") Has anyone encountered this before? I've minify_js to False in hopes to exclude the GA script but keep on getting the console error. Would love to hear any tips or workarounds for the best way to exclude GA tracking code from compression/minification. Thanks! -
Webapp deployment issue in shared hosting
Can anyone tell me how I can deploy my Django React-based webapp in my shared hosting -
FileNotFoundError: Could not find module 'gdal.dll' when running Django with GeoDjango on Windows (Conda environment)
I'm working on a Django project using GeoDjango for spatial models. I'm on Windows 10, using a Conda environment (moodspend). When I try to run the server with: python manage.py runserver I get this error: (moodspend) PS C:\Users\ngari\Desktop\Ngari's Projects\moodspend\backend> python manage.py runserver {"timestamp": "2025-06-12T20:26:05.871837Z", "level": "INFO", "logger": "django.utils.autoreload", "message": "Watching for file changes with StatReloader", "module": "autoreload", "function": "run_with_reloader", "line": 667, "thread": 14264, "process": 15528, "correlation_id": "e0dfc999"} Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\ngari\miniconda3\envs\moodspend\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Users\ngari\miniconda3\envs\moodspend\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\ngari\miniconda3\envs\moodspend\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ngari\miniconda3\envs\moodspend\lib\site-packages\django\core\management\commands\runserver.py", line 124, in inner_run autoreload.raise_last_exception() File "C:\Users\ngari\miniconda3\envs\moodspend\lib\site-packages\django\utils\autoreload.py", line 86, in raise_last_exception raise _exception[1] File "C:\Users\ngari\miniconda3\envs\moodspend\lib\site-packages\django\core\management\__init__.py", line 394, in execute autoreload.check_errors(django.setup)() File "C:\Users\ngari\miniconda3\envs\moodspend\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\ngari\miniconda3\envs\moodspend\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ngari\miniconda3\envs\moodspend\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "C:\Users\ngari\miniconda3\envs\moodspend\lib\site-packages\django\apps\config.py", line 269, in import_models self.models_module = import_module(models_module_name) File "C:\Users\ngari\miniconda3\envs\moodspend\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", … -
How can I send a column from one field of the queryset model to the form?
Good day! I have a model table. And a form. I filter the query from the queryset model by certain criteria and send it to the code in views. From the filtered queryset I would like to take only one column - according to one field of the model. And convert this column from one field to a list or another element. How can I send a column from one field of the queryset model to the form? As the names of the fields in the form something like verbose_name= How can I send a column from one field of the queryset model to the form? Good day! I have a model table. And a form. I filter the query from the queryset model by certain criteria and send it to the code in views. From the filtered queryset I would like to take only one column - according to one field of the model. And convert this column from one field to a list or another element. How can I send a column from one field of the queryset model to the form? As the names of the fields in the form something like verbose_name=. -
How do I write a Django ORM query that returns a match based on an intersection of lists?
If I have, for example: from django.contrib.postgres.fields import JSONField class MyModel(models.Model): data = JSONField() GIVEN a model instance obj1, where data == ['apple', 'banana', 'orange'] GIVEN a model instance obj2, where data == ['banana', 'orange'] GIVEN a model instance obj3, where data == ['apple'] How can I write an ORM query that returns all model instances whose data includes at least one item from a given list, ['apple', 'strawberry']? It should return obj1 and obj2 because both of those objects include 'apple', despite the argument including 'strawberry', which is not represented in any of the objects. -
Should I really use React/Vue with Django instead of Alpine.js?
I have a page where user creates an instance. An instance has a bunch of characteristics and foreign key to product (which has category and name itself) and all the fields are static - just stylized selects and inputs, but there is just a change event handler which saves any changes in session so that user could go back to editing With Alpine.js I replaced two selects (where user chooses product category and product name) with a single button - "select a product" and after clicking a modal appears with options depending on the step - either category or name, once both category and name are selected a card with this product appears and a button turns into "change a product". Everything worked just fine until I started filling this with initial values from draft form, so that you need to combine Django {% if %} with Alpine.js x-if which caused flickering. Is it really worth it to switch React/Vue + DRF or am I missing something? Considering my codebase it would be painful, but pretty much possible. The only negative thing that stops me from doing it right now is Django features I don't want to rewrite in JS … -
How can I convert the last / any row of a model / queryset into one dictionary?
Good day! I have a table model. I plan to take one row from it - one set of elements. To place it in an object - a dictionary. How can I place the last or first or a specific one row from a model / queryset into a dictionary - not in a list of dictionary sets, but in one dictionary. One row of a model / queryset into one dictionary? How can I convert the last / any row of a model / queryset into one dictionary? -
React + React Native + Django AllAuth
I'm running a Django server which has API's I consume through a React Native and React applications. I want it to work for Google, Facebook, Instagram and Twitter. For this question I want to focus on the React Application and Google Authentication and hopefully it will be repeatable for my other social options. My React Application manages to login just fine for Google It returns field called "credentials". My thinking was I can send this to Django AllAuth, which would call google and then return user data, which I can create a Django User and sign in and if that user already has an account it just login. Some features on the API require users to have loggedin. I have the same client_id for my React and Django app. Does AllAuth do this already ? How do I work with it? When I try forward my 'credentials' (the one google returned to my React) to auth/google/ I get a 403. I would imagine I don't have to do this pragmatically as this seems like a pretty common setup . Any guidance on how I can make these React and Django AllAuth work together would be great. -
Django Sitemap issue: GSC fail to fetch sitemap with error "Sitemap could not be read"
I created sitemap using django default sitemap from django.contrib.sitemaps.views import sitemap Here is the complete process #urls.py sitemaps = { 'static': StaticViewSitemap, 'blogpost_detail': BlogSitemap, 'portfolio-details': PortfolioSitemap, # Add others like 'posts': PostSitemap if needed } path( "sitemap.xml", sitemap, {"sitemaps": sitemaps}, name="django.contrib.sitemaps.views.sitemap") I can access sitemap at https://dataguru.cc/sitemap.xml but upon submission i get "Sitemap could not be read", I have tried these few things so far Reduced the size of sitemap to single link to verify Added rule in cloudflare to bypass compression and cache for /sitemap.xml since its created by django but still verified syntex of xml using online tools Used static sitemap.xml from template view changed the name from sitemap.xml to site_map.xml So far nothing is working so i would appreciate any help, if it has something to do with my django app or something else.. Additionally i have a middleware that doesn't interfere with requests but i have disabled it and result is just the same.