Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Duplicate validation message in Django contact form with Bootstrap 5 and Crispy Forms
I have a contact form in Django that I've styled using Bootstrap 5 and Crispy Forms. The form includes validations on fields, such as email validation and required fields. The issue I'm facing is that the validation message is being duplicated on the page when an error occurs. For example, if I submit the form without filling in the email field, two identical error messages appear. I've reviewed my code and templates multiple times, but I can't seem to find the cause of the duplication. Here's my relevant code: [forms.py] from crispy_bootstrap5.bootstrap5 import FloatingField from crispy_forms.helper import FormHelper from crispy_forms.layout import Div, Submit from django import forms from django.core.validators import EmailValidator class CustomSubmit(Submit): field_classes = "btn btn-outline-primary" class FormularioContacto(forms.Form): nombre = forms.CharField( label='Nombre', max_length=50, required=True, ) email = forms.EmailField( label='Email', required=True, validators=[EmailValidator()], error_messages={'invalid': 'Correo electrónico no válido'}, ) contenido = forms.CharField( label='Mensaje', widget=forms.Textarea(), required=False, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'formularioContacto' self.helper.form_class = 'formulario' self.helper.form_method = 'post' self.helper.attrs = {'novalidate': True} # Add 'novalidate' attribute to the form self.helper.layout = Div( Div( Div( FloatingField('nombre'), FloatingField('email'), FloatingField('contenido'), Div( CustomSubmit('Enviar', 'submit', css_class='btn-lg'), css_class='text-center mt-3' ), css_class='col-md-6 mx-auto' ), css_class='row' ), css_class='container my-4' ) [views.py] import smtplib … -
How should I add custom validation to the Django admin for a non-standard model field?
I have a non-standard Django model field (pg vector list/array) which is resulting in a validation error when the admin application attempts to naively validate it: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() I have tried specifying a vector-specific validation function using the model field's validators list, overriding the models clean method, etc. without success. What would be the appropriate way of handling this? -
How to define a Django model for your historical table,
Let's assume the model is named RateHistory and contains the fields rate and updated_date from django.db.models import F def get_rate_changes(): previous_rate = None rate_changes = [] for record in RateHistory.objects.order_by('updated_date'): if previous_rate is not None and previous_rate != record.rate: rate_changes.append(record.updated_date) previous_rate = record.rate return rate_changes After implementing the code and calling the get_rate_changes function, you should expect to retrieve a list of updated dates when the rate changed in your RateHistory table -
GitHub Action Error: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' while deploying on Azure App Service
I built a simple Django application and am trying to deploy it using Azure App Service and GitHub Actions CI/CD. While deploying, I am getting the error- Here is my project directory structure- Can somebody please help me understand what the issue is here? I came accross this answer but this is not working for me- GitHub for Django on Azure: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' -
trying to Dockerize a Django/Pyhton project, with no success
I'm trying to dockerize a backend project, made with django/python and postgreSQL It works as an api, its structure is: backend api models.py urls.py views.py ... menu_back manage.py settings.py Dockerfile requirements.txt But I get an error saying that moule backend can't be found This is my Dockerfile: # Use an official Python 3.11.2 runtime as the base image FROM python:3.11.2 # Set the working directory in the container WORKDIR /app/backend # Copy the requirements file into the container COPY requirements.txt . # Install the Python dependencies RUN pip install --no-cache-dir -r requirements.txt # Copy the Django project code into the container COPY . . # Set environment variables for PostgreSQL ENV POSTGRESHOST=db ENV POSTGRESPORT=5432 ENV POSTGRESUSER=postgres ENV POSTGRESPASSWORD=mypassword ENV POSTGRES_DB=mydatabase CMD python menu_back/manage.py runserver 0.0.0.0:8000 # Expose the port on which the Django server will run EXPOSE 8000 I move to the backend directory and execute 'docker build -t backend-image -f Dockerfile .' it runs ok, but when trying to run it with 'docker run -p 8000:8000 backend-image', I get this error: ModuleNotFoundError: No module named 'backend' In the file manage.py, I have os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.menu_back.settings") I don't know how to fix it, even chatgpt is cycling with answers but the … -
Adding Embedded HTML to Email Messages in Django
I'm trying to add an Embedded HTML to an Email to send an Image in it, but image doesn't seem to appear in here, I reviewed another solutions but nothing seems to result views: img_path = os.path.join(settings.BASE_DIR, 'Mods\Surveys\static\images\Survey.jpg') print(img_path) html_content = render_to_string('email_template.html', { 'survey': survey, 'url': survey.url, 'path': img_path, }) msg = EmailMultiAlternatives( subject=survey.subject, body=strip_tags(html_content), from_email='my email', to=[respondant.email] ) msg.attach_alternative(html_content, "text/html") msg.send() template: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <h1>{{ survey.subject}}</h1> <p>{{ survey.body}}</p> <a href="{{ url }}"><img src="{{ path }}" alt="Image"></a> </body> </html> Email is sent with subject body and the url, but image doesn't appear As I said, I reviewed another solutions but nothing seems to help -
How to create a manytomany relation in django to models with different data type primary key
I have a model whose primary key is of Integer field datatype and I want to have a manytomany field inside it of another model whose primary key is of Char field. class A(models.Model): count = models.IntegerField(default=0) link = models.ManyToManyField(B, null=True) class B(models.Model): test = models.CharField(primary_key=True, max_length=36) When I used this method I got this error: (errno: 150 "Foreign key constraint is incorrectly formed") I got to know that a association table is required, but don't know how to apply it. -
Django: ModuleNotFoundError. No module named 'myApp'
I am using termux I created a virtual environment, started django project, cd into the second directory of my project, and started an app. Here is the arrangement of my dir. and files I added the app to the INSTALLED_APP in setting.py INSTALLED_APPS in settings.py When I run 'python manage.py runserver, I get an error: ModuleNotFoundError. No module named 'myApp_name' Error message after running 'python manage.py runserver' Please help me resolve this issue. I am a beginner and have been on this for two days I am stuck and can't learn further. I expect 'python manage.py runserver' to run without an error, since I started an app and added its name to INSTALLED_APP -
How to run celery in django from docker
I learn docker and don't understand why celery can't connect to rabbitmq. I've created 2 images for rabbitmq and django, here is my docker-compose: version: "3.0" services: # WEB django: build: . volumes: - media_volume:/website/journal_website/media - static_volume:/website/journal_website/static - database_volume:/website/journal_website/database ports: - "8000:8000" depends_on: - rabbit # RabbitMQ rabbit: hostname: rabbit container_name: rabbitmq image: rabbitmq:3.12-rc-management environment: - RABBITMQ_DEFAULT_USER=simple_user - RABBITMQ_DEFAULT_PASS=simple_password ports: # AMQP protocol port - "5672:5672" # HTTP management UI - "15672:15672" restart: always volumes: media_volume: static_volume: database_volume: my broker configuration in settings.py in django: CELERY_BROKER_URL = 'amqp://localhost:5672' celery.py file: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "website.settings") celery_application = Celery("website") celery_application.config_from_object("django.conf:settings", namespace="CELERY") celery_application.autodiscover_tasks() entrypoint.sh that's used as entrypoint in Dockerfile: #!/bin/bash # Start Celery celery -A website worker -l info # Run Django server python3.11 manage.py runserver 127.0.0.1:8000 and Dockerfile: # Many many commands to install python and all dependencies in ubuntu 20.04 # Run Django server EXPOSE 8000 ENTRYPOINT ["/entrypoint.sh"] I use Docker Desktop on Windows 10, when I run docker compose up or run container in desktop application I get such error: [Date: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused., I've checked that localhost is 127.0.0.1. What should I … -
Django: Implementing a dependent dropdown list in a form
Hello StackOverflow community! I am new to programming and am currently working on a Django-based website for ITSM ticket management. My site has two main components: A ticket manager that displays created tickets, their status, address, assigned technician, problem description, etc. An administrative part in Django, which only certain users have access to. I am having trouble implementing a ticket creation or update form. I am trying to implement a dependent dropdown list functionality: when a district is selected in the ticket creation form, only a list of technicians associated with that district should be displayed in the "Technician" field. I am unsure of how to correctly implement this functionality. Maybe I should use JavaScript or AJAX, or is there a way to do this directly in Django? Your guidance or pointers would be highly valuable. Thank you for your assistance! **models.py** `from django.db import models from django.utils import timezone from django.utils.formats import date_format from django import forms class Ticket(models.Model): STATUSES = ( ('new', 'Новый'), ('in_progress', 'В работе'), ('overdue', 'Просрочен'), ('deferred', 'Отложенный') ) DEVICE_CHOICES = [ ('Выберите тип прибора', 'Выберите тип прибора'), ('Stemax', 'Stemax'), ('Приток', 'Приток'), ('Болид', 'Болид'), ('Альтоника', 'Альтоника'), ] title = models.CharField(max_length=200, default='Default Title') # Добавлено новое поле … -
Cache API for requested ID for specific time / Django admin filter
I'm learning python for few weeks and I'm creating hockey app. I have two problems. text In this API we have about 1000 players with specific ID. I know how I get specific value and how I create for loop for all values, but I don't want send request for all players (ofc) and store this values in a database or send request every time when some app user want it. So when user send request for example for Ovechkin, for McDavid..., how I could cache this for some time because data should be updated - if they play another match? Should I do something in Redis or django-cache? I created models in Django - Team, League, Fixture. I added teams and assign them League(NHL, SHL, DEL etc.) and for fixture? I chose league NHL and saw all teams(included from Germany, Sweden) still. How I can create live filter in Django Admin when I click on NHL = all non-NHL teams disappear. class League(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Team(models.Model): name = models.CharField(max_length=128, unique=True) league = models.ForeignKey(to=League, on_delete=models.CASCADE, null=True) def __str__(self): return self.name class Fixture(models.Model): league = models.ForeignKey(League, on_delete=models.CASCADE, related_name='fixtures') home_team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='home_games') away_team = … -
Django NoReverseMatch - content doesn't load properly
I have a blog app in my Django project that is based on this tutorial. With the link to the blog placed in my main.html template, the site throws a NoReverseMatch error. I can't seem to figure it out. Here's the HTML: <li class="nav-item"><a href="{% url 'blog' %}" class="nav-link" id="header">Blog</a></li> Here's the urls.py code: from django.contrib import admin from main import views from django.conf.urls import include from django.urls import path from main.views import dashboard, register, about, blog from django.conf import settings from django.conf.urls.static import static app_name = 'main' urlpatterns = [ path('', views.main, name='main'), path('admin/', admin.site.urls), path('dashboard/', dashboard, name='dashboard'), path('accounts/', include('django.contrib.auth.urls')), path('register/', register, name='register'), path('about/', about, name='about'), path('blog/', include('blog.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Here's the other urls.py: # main/urls.py from django.urls import path, include from main.views import dashboard, register app_name = 'main' urlpatterns = [ path('blog/', blog, name='blog'), ] Here's the views.py code: # main/views.py from django.http import HttpResponse from django.contrib.auth import login as auth_login from django.shortcuts import redirect, render from django.urls import reverse from main.forms import CustomUserCreationForm # Create your views here. def main(request): return render(request, 'main.html', {}) def dashboard(request): return render(request, 'users/dashboard.html') def admin(request): return render(request, 'admin') def login(request): return render(request, 'registration/login.html') def register(request): if request.method == 'GET': … -
combine values with select_related
I have to models "Product" and "user" and post model has user foreignKey I want to query posts join with user with only ("username","name) fields I tried to use Product.objects.values('id', 'title',"user__username","user__name") and i got { id, title, username, name } but i want something like this { id, title, user:{ username, name } } -
How to avoid Graphene sorting an OrderedDict on query response? (Python, Django)
I am trying to return a dict of OrderedDicts from a Graphene endpoint in a Django application, by using the GenericScalar type field. The OrderedDicts are sorted based on value, but the API seems to re-sort the dicts by key. The OrderedDicts items format is: { id : [name, amount] } Example of one of the OrderedDicts that I send: { 'foods': { 3: ['apple', 5], 1: ['banana', 7], 2: ['carrot', 3] }, 'animals': { 5: ['cat', 3], 3: ['dog', 10], 1: ['pig', 5], } } What is received in the endpoint response: { 'foods': { 1: ['banana', 7], 2: ['carrot', 3], 3: ['apple', 5], }, 'animals': { 1: ['pig', 5], 3: ['dog', 10], 5: ['cat', 3], } } I am specifically using OrderedDicts because the order is important, but I have not found a way of avoiding Graphene to re-sort the OrderedDicts by key. This is the how the ObjectType and Query are declared, althought is is nothing out of the ordinary. class DashboardType(g.ObjectType): data = GenericScalar() class Query(object): dashboard = Field(DashboardDataType, id=ID(), date=Date()) def resolve_dashboard(self, info, **kwargs): data = function_to_get_the_data(kwargs) # up until this point the data is still sorted correctly return data The data is sorted as … -
Booking Cycle with Django
I have an app where the user books a session and then pay it using payment service provider (like Fawry or Paymob which are middle-east based companies). the way this is done is when the user books a session or multiple sessions a code is generated and it will be available for say 30 mins. My Question is : should I declare the sessions that the user is going to pay for as booked so when another user fetches the sessions they will not be available to be booked? and if so what happens if the user decided not to pay for the sessions, how would I know? and if I can know and return them back to unbooked status what if the other user that wanted them didn't check for these sessions again? OR should I make them available until the user pay for them then remove them from the available sessions, but then what if two users booked the same session -as it's not yet been removed when one user booked it-, the generated code that they are going to use has an amount of money to be paid it will not check if the session that the … -
How to Merge Byte Files Together in Python
I am running into a situation where I need to generate multiple filled PDF forms, I have the data filled out and the 'bytes' file is accessible, but when I attempt to combine the 2 files in their byte representation, nothing happens, the file is overridden and the original is the only thing shown. What am I doing wrong, this seems like it should be easy. # don't worry about these, they are filled PDFs in byte form, this works as expected. pdf1 = PDFFormManager.fill_with_jinja(file=template, data=data) pdf2 = PDFFormManager.fill_with_jinja(file=template, data={}) # here is the issue print(len(pdf1), len(pdf2)) # 177354 177354 print(type(pdf1), type(pdf2)) # <class 'bytes'> <class 'bytes'> print(len(pdf1+ pdf2)) # 354708 # when I return this, I only get the single pdf, not the concatenated one response = HttpResponse(pdf1+pdf2, content_type=f"application/pdf") -
How to translate simplejwt error (django rest framework)?
What is the best way to translate the error: "No active account found with the given credentials" coming from: from rest_framework_simplejwt.views import TokenObtainPairView ... urlpatterns = [ path('token/', TokenObtainPairView.as_view()), I use React on the frontend and Django and Django Rest Framework on the backend. I changed django settings to: LANGUAGE_CODE = 'pl' but this apparently didn't change the simplejwt error language. -
Django web development pdf [closed]
I want all the pdf to be displayed on the webpage from the database and one can see it from there… The display part is done but whenever i click on a pdf the page loads and gets redirected to the same page and pdf doesn’t open… what should I do? I tried everything but it won’t solve -
I am getting error for Deploying django project on vercel can anyone help me with this
enter image description here i am getting error like this I have tried so many ways to fix it but it didn't help. I think the error must be in selecting the framework preset for Django on Vercel while deploying, I think so. I have selected "OTHER" for Django deployment as suggested on youtube tutorials. -
I am getting raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?
My settings.py looks like this and I have created a db with name student in mysql. Despite having installed mysqlclient latest version I am getting this error. I tried with using other database setup but still got similar error. """ Django settings for studentReportCard project. Generated by 'django-admin startproject' using Django 4.2.3. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-%38#(h6gd4$$2%n7+-3v3#-n)mcaobie=)1o&f()+&8m!+oq)!' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'report_card', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'studentReportCard.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'studentReportCard.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'USER': 'root', 'NAME': 'student', … -
Django crispy_forms using
I have been using crispy_forms for my form on django project. But While Project is running. A problem A problem appears suddenly. how can I solve this problem on my project ? can you help me ? I have to go on this project very faster [[[enter image description here](https://i.stack.imgur.com/x8kr2.png)](https://i.stack.imgur.com/UF8XI.png)](https://i.stack.imgur.com/fDG6k.png) -
Im trying to make a Instagram reel downloader and keep getting this error Expecting "property name enclosed in double quotes: line 1 column 2 (char 1)
Im using django to create a instagram reel downloader but it keeps giving me json errors My code: from django.shortcuts import render , redirect from instascrape import * import json import time # Create your views here. def index(request): if request.method == "GET": return render(request, "index.html") else: if request.POST['url']: google_reel = Reel("https://www.instagram.com/reel/CumvX9VgNQt/?utm_source=ig_web_copy_link&igshid=MzRlODBiNWFlZA==") google_reel.scrape() google_reel.Download(fp = "{path\filename.mp4}") else: return render(request, "index.html", { "error": "Invalid url" }) return redirect("/") The error im getting is "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)" im thinking it is a python package problem the one im using is instascrape (https://github.com/chris-greening/instascrape) -
How to send message through django-channels from asyncio loop with add_reader
I am trying to listen for notifications from postgres database and send message through django-channels on each row insertion, for that I want to use asyncio loop, where I am adding reader for connection. However, I am receiving following error on attempt to use async_to_sync: RuntimeError: You cannot use AsyncToSync in the same thread as an async event loop - just await the async function directly. Here is my code: import asyncio import logging import channels.layers from asgiref.sync import async_to_sync from django.conf import settings from django.core.management.base import BaseCommand from django.db import connections channel_layer = channels.layers.get_channel_layer() logger = logging.getLogger(__name__) class Command(BaseCommand): def handle(self, *args, **options): conns = [(connections[db].cursor().connection, db) for db in settings.DATABASES] loop = asyncio.get_event_loop() for conn, db in conns: conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) cursor = conn.cursor() cursor.execute("LISTEN event_changed;") loop.add_reader(conn, partial(self.handle_notify, conn=conn, db=db)) logger.info("Starting runlistener loop.") loop.run_forever() def handle_notify(self, conn, db): conn.poll() for notify in conn.notifies: logger.debug(f"new event received on db {db}: {notify.payload}.") async_to_sync(channel_layer.group_send)( db, {"type": "on_new_event", "event": notify.payload} ) conn.notifies.clear() I can't use await in handle_notify since it is not async function and I couldn't find any way to use async function as a callback for add_reader. I've managed to implement this functionality without asyncio, by simply checking connection with select.select in … -
How can fix ' Error: No application module specified.' on DigitalOcean
I am getting ' Error: No application module specified. ' error while I'm trying to deploy my django project. After Successful Build, Digital Ocean is trying deploy it and raise this error after short time. Can you help me about this? Where should I change? settings.py >>> """ Django settings for djcrm project. Generated by 'django-admin startproject' using Django 4.2.2. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path import os from dotenv import load_dotenv # .env dosyasını yükle load_dotenv() DEBUG = os.getenv('DEBUG') # SECRET_KEY'i al SECRET_KEY = os.getenv('SECRET_KEY') # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', #third party apps 'crispy_forms', "crispy_tailwind", 'tailwind', #local apps 'leads', 'agents', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'djcrm.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / "templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'djcrm.wsgi.application' # Database # https://docs.djangoproject.com/en/4.2/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": … -
Query many to one backward relation Django
I have these 2 models: class User(models.Model): full_name = models.CharField(max_length=255) class WorkSchedule(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) day_of_week = models.IntegerField() start_time = models.TimeField() end_time = models.TimeField() Is it possible for me to use a single query here to get back something like this: { "id": 1, "full_name": "User name", "work_schedule": { { "day_of_week": 1, "start_time": 8:00, "end_time": 20:00 }, { "day_of_week": 2, "start_time": 8:00, "end_time": 20:00 } } }