Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python Django Error during rendering "template"
This is what im building I am currently developing a receipt system and when i run the application, i get this error, i have checked the settings.py and my app has been added to the list of installed apps, my templates are also in place and the problem is still existent,please assist if there is somewhere else i need to check , Below is the error i get when i try run the application This is the error Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 5.2.1 Python Version: 3.12.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'receiptsiclife'] Installed 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'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.filesystem.Loader: /home/aessumen/receiptsystemsiclife/receiptsystemsiclife/templates/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/aessumen/receiptsystemsiclife/venv/lib/python3.12/site-packages/django/contrib/admin/templates/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/aessumen/receiptsystemsiclife/venv/lib/python3.12/site-packages/django/contrib/auth/templates/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /home/aessumen/receiptsystemsiclife/receiptsystemsiclife/receiptsiclife/templates/base.html (Source does not exist) Template error: In template /home/aessumen/receiptsystemsiclife/receiptsystemsiclife/receiptsiclife/templates/receiptsiclife/home.html, error at line 1 base.html 1 : {% extends 'base.html' %} 2 : 3 : {% block title %}Dashboard - ReceiptSicLife{% endblock %} 4 : 5 : {% block content %} 6 : <div class="row"> 7 : <div class="col-md-12"> 8 : <h1>Dashboard</h1> 9 : … -
Best SMS Service Provider for Global OTP Verification and Phone Number Validation (Any Free Options?) [closed]
I'm implementing OTP verification for user signup/login in my application and I need a reliable SMS service provider. My main goals are: Global Reach – The service should support sending SMS OTPs to users in multiple countries. OTP Verification – Fast and reliable OTP delivery is essential. Phone Number Validation – I’d like to validate if a number is real/reachable before sending the OTP. I’ve found a few providers like: Twilio MessageBird Nexmo (Vonage) Firebase Phone Auth D7 Networks My Questions: Which SMS service is best for global OTP delivery in terms of reliability and cost? Are there any services that also provide real-time phone number validation (e.g., like Twilio’s Lookup API)? Are there any free or low-cost SMS services or workarounds (especially for development/testing)? Is it worth using a separate phone validation API before sending OTPs? Besides SMS, are there any alternative methods to verify a phone number (e.g., missed call verification, WhatsApp, flash call, etc.)? If you’ve had experience with any of these (or others), I’d really appreciate your recommendations. Thanks in advance! -
is anyone faced this issue : SSL CERTIFICATE_VERIFY_FAILED certificate verify failed: Hostname mismatch, certificate is not valid for 'smtp.gmail.com'
When deploying an Django full stack app on GoDaddy VPS I came across this error, I have also changed server the the error still persists, my application use Celery for email tasks queues with Redis, I do not know what to do can you guys help me this is really an big problem. ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: Hostname mismatch, certificate is not valid for 'smtp.gmail.com'. (_ssl.c:1147) """ Django settings for xxxxxxx project. Generated by 'django-admin startproject' using Django 4.2.20. 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 from dotenv import load_dotenv import os from celery.schedules import crontab load_dotenv() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 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 = '.......' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True if os.getenv('DJANGO_ENV') == 'production': DEBUG=False ALLOWED_HOSTS = ['xxxxx.com','127.0.0.1','localhost'] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'api', 'react_frontend', 'rest_framework', 'celery', … -
Python Django Admin Form: show inline without rendering a form
I have a Django admin page which allows me to edit a model in my domain. The ModelAdmin looks like this: @admin.register(models.VehicleTemplate) class VehicleTemplateAdmin(ModelAdminBase): list_reverse_relation_inline = False search_fields = ["name", "description"] list_display = ["name", "description", "parent", "status"] inlines = [VehicleInline] readonly_fields = [ "config", "status", "properties" ] fields = [ "step", "name", .... ] ... class VehicleInline(InlineModelAdmin): model = models.Vehicle def has_add_permission(self, request, obj=None): return False def has_change_permission(self, request, obj=None): return False def has_delete_permission(self, request, obj=None): return False .... The VehicleInline can contain thousands of child models of VehicleTemplate, which ends up rendering thousands of inline forms which all get submitted together when the admin change form is submitted/saved. However, nothing in the VehicleInline is editable. So, instead, I would like to simply display the contents of these child models without rendering any form or input elements. The root problem I have is that the number of form elements is more than the absolute_max configured in Django so it fails the form submission even though none of the inline data is editable. I have tried many, many ways of preventing the form widgets from rendering by providing empty widgets and editing the InlineModelAdmin to not include the input HTML but … -
Django-allauth - Make phone number optional for SocialLogin
I am using django-allauth in my project and I have configured Google as a SocialAuth provider. I have a custom signal receiver that updates the phone number on the SocialAuthAccount after the user signs up. But currently the system throws an error when the user logins via SocialAuth if they do not have a public phone number on their account. I am getting an error - KeyError 'phone' at - allauth/account/internal/flows/phone_verification.py - line 46. This is my relevant settings.py: ACCOUNT_LOGIN_METHODS = {"phone", "email", "username"} ACCOUNT_SIGNUP_FIELDS = [ "phone*", "email*", "username*", "password1", "password2" ] How can I tell the SocialAuthAdapter that phone number is optional and might not be there? -
decouple.UndefinedValueError: SECRET_KEY not found when using python-decouple in Django
I'm getting the following error when I try to run my Django project: decouple.UndefinedValueError: SECRET_KEY not found. I'm using python-decouple to manage environment variables. In my settings.py, I have: from decouple import config SECRET_KEY = config('SECRET_KEY') I’ve already created a .env file in the root directory of my project with the following line: SECRET_KEY=my-very-secret-key But the error still appears. I’ve confirmed that the .env file exists and contains the SECRET_KEY. Things I’ve already checked: ✅ .env is in the same directory as manage.py ✅ File is named .env, not something like env.txt ✅ There are no spaces around the equal sign (i.e., SECRET_KEY = my-key is incorrect) ✅ I’ve restarted the server after creating the .env file Is there something I’m missing about how decouple loads the .env file in Django? Any help would be appreciated! Check Error traceback showing SECRET_KEY not found when using python-decouple -
Django: Migrations generated again after deployment, even though no model changes were made
As part of our project, we made some changes, merged the PRs, and deployed the latest code to our development server. However, after deploying, we noticed that Django is generating new migrations, even though there were no changes made to any of the models in our Django apps. We’re unsure why this is happening. Could someone help us understand why migrations might be triggered again in this case, and how to prevent unnecessary migrations from being created or detected? Any guidance would be appreciated! -
Is there an app available to Test emails locally using a local SMTP server on Linux and Windows
I want to test emails from django app, i was using mailtrap before but now i want to test my emails locally. For Django developers, transitioning from a remote email testing service like Mailtrap to a local solution is often a strategic decision driven by the inherent limitations of external platforms during the rapid development cycle. While Mailtrap offers convenience for initial setup and demonstration, its free tier constraints, such as limited email volume or slower delivery due to network latency, can impede efficient iteration. Moving to a local SMTP server eliminates reliance on internet connectivity, provides instantaneous email capture for immediate feedback, and offers unrestricted testing capacity. This shift not only streamlines the development process by making email debugging faster and more private, but also ensures a cost-free and fully controllable environment tailored to the dynamic needs of local application testing. -
Combine multiple `shell` commands across apps using `get_auto_imports`?
Django 5.2 introduced the ability to customize the shell management command by overriding the get_auto_imports() method in a management command subclass (see the release note or this page of the doc). That's a nice feature and it works well for a single app, but I'm running into trouble trying to make it scale across multiple apps. For instance, in app1/management/commands/shell.py: from django.core.management.commands import shell class Command(shell.Command): def get_auto_imports(self) -> list[str]: return [ *super().get_auto_imports(), "app1.module1", ] And in app2/management/commands/shell.py: from django.core.management.commands import shell class Command(shell.Command): def get_auto_imports(self) -> list[str]: return [ *super().get_auto_imports(), "app2.module2", ] The issue is that only one of these is picked up by Django — whichever app comes first in INSTALLED_APPS. This seems to be by design, as Django only uses the first matching management command it finds. Is there a clean way to combine auto imports from multiple apps or extend the shell command across apps without having to manually centralize everything in one location? I’m looking for a generic and scalable solution that allows each app to contribute its own imports to the shell, ideally still using get_auto_imports() so the logic stays clean and encapsulated per app. -
Issue with browser-tools@2.0.0 from circleci
I am trying to run Selenium tests for a Django app on CircleCI. The browser tools are updated 28.05.2025, but I still can't manage to configure it... In my config.yml I have version: 2.1 orbs: python: circleci/python@3.1.0 slack: circleci/slack@4.10.1 browser-tools: circleci/browser-tools@2.0.0 .... build-and-test: executor: my-executor parallelism: 16 steps: - checkout - browser-tools/install-chrome - run: name: Install ChromeDriver 136.0.7103.94 command: | CHROMEDRIVER_VERSION=136.0.7103.94 wget -q -O /tmp/chromedriver_linux64.zip https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/${CHROMEDRIVER_VERSION}/linux64/chromedriver-linux64.zip unzip -o /tmp/chromedriver_linux64.zip -d /tmp/ sudo mv /tmp/chromedriver-linux64/chromedriver /usr/local/bin/chromedriver sudo chmod +x /usr/local/bin/chromedriver - run: name: Show Chrome and ChromeDriver versions command: | google-chrome --version chromedriver --version but for some reason browser-tools is trying to install Firefox instead and getting an error. -
Django test fails on github-actions, works locally
I am ahving a problem. I am following a tutorial and wrote a wait for db command in my django project to wait until db is available and then run my tests. The command is below: docker compose run --rm app sh -c "python manage.py wait_for_db && python manage.py test" When I run this command on my terminal, it executes fine. However, I have a github action on run this command as soon as my code is pushed, I am getting an error when that heppens, and I am unable to comprehend the log. The yml file for github action is below: --- name: Checks on: [push] jobs: test-lint: name: Test and Lint runs-on: ubuntu-24.04 steps: - name: Login to Docker Hub uses: docker/login-action@v3 with: username: ${{ secrets.DOCKERHUB_USER }} password: ${{ secrets.DOCKERHUB_TOKEN }} - name: Checkout uses: actions/checkout@v4 - name: Test run: docker compose run --rm app sh -c "python manage.py wait_for_db && python manage.py test" - name: Lint run: docker compose run --rm app sh -c "flake8" Though most of the log part says success, I am unable to identify the error, it is probably only on the last line. The full error message says this: Run docker compose … -
django problem, when I pass product id by get method
In href tag I want to send product id but this code showing an error. Could not parse the remainder: 'data.id' from ''viewproduct'data.id' {% for data in data %} <div class="item mt-5"> <div class="card" > **<a href={% url 'viewproduct'data.id %}>** <img class="women" src="{{data.image.url}} "alt="First slide"> </div> <div class="card-body text-center"> <h4>{{data.name}}</h4> </div></a> </div> {% endfor %} -
What Python topics should I learn first as a beginner, and where can I find free resources to practice them?
I'm a computer science student currently learning web development and just getting started with Python. I've covered some basics like variables, data types, and simple loops, but I'm not sure what to focus on next or how to build a strong foundation. Specifically, I would like to know: What are the core Python concepts I should learn first as a beginner? Are there free and reputable resources or platforms where I can learn and practice these concepts interactively? How can I apply what I learn through small projects or exercises? I’m trying to learn efficiently and build practical skills, so suggestions that help with hands-on learning are appreciated. Please avoid paid course recommendations—I’m only looking for free resources and beginner guidance. -
multiple permissions for multiple roles in django
im currently working on a news project which i have news-writer , article-writer etc . im using proxy models , i created a base User model and i created more user models in the name of NewsWritetUser and it has inherited in Meta class in proxy model from my base User model . i have a problem , a user , can be news_writer , article writer and etc together , i want to create a permission system to handle it , this is my models.py : `from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from home.urls import app_name class User(AbstractBaseUser , PermissionsMixin): USER_TYPE_CHOICES = [ ('chief_editor', 'Chief Editor'), ('news_writer', 'News Writer'), ('article_writer', 'Article Writer'), ('hadith_writer', 'Hadith Writer'), ('contactus_admin', 'Contact Us User'), ('none' , 'No Specified Duty') ] email = models.EmailField(max_length=225 , unique=True) phone_number = models.CharField(max_length=11 , unique=True) full_name = models.CharField(max_length=100) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default = True) is_superuser = models.BooleanField(default = False) national_id = models.CharField(max_length=15 , unique=True) date_joint = models.DateTimeField(auto_now_add=True) duty_type = models.CharField(max_length=30 , choices=USER_TYPE_CHOICES , default='none') USERNAME_FIELD = 'national_id' REQUIRED_FIELDS = ['email' , 'phon_number' , 'full_name' , 'national_id'] def __str__(self): return f' ID : {self.national_id} - Name : {self.full_name} - Phone : {self.phone_number} … -
Django + Celery + PySpark inside Docker raises SystemExit: 1 and NoSuchFileException when creating SparkSession
I'm running a Django application that uses Celery tasks and PySpark inside a Docker container. One of my Celery tasks calls a function that initializes a SparkSession using getOrCreate(). However, when this happens, the worker exits unexpectedly with a SystemExit: 1 and a NoSuchFileException. Here is the relevant part of the stack trace: SystemExit: 1 [INFO] Worker exiting (pid: 66009) ... WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... WARN DependencyUtils: Local jar /...antlr4-4.9.3.jar does not exist, skipping. ... Exception in thread "main" java.nio.file.NoSuchFileException: /tmp/tmpagg4d47k/connection8081375827469483762.info ... [ERROR] Worker (pid:66009) was sent SIGKILL! Perhaps out of memory? how can i solve the problem -
Django overwriting save_related & copying from linked sql tables
In django python, I am able to overwrite the save_related function (when save_as = True) so the instance I am trying to copy is saved and copied properly. When I save, though, I want other objects in other tables linked by an ID in the sql database that should be copied when the. For example we have table A, and I can copy instances in A, but I need B, a related sql table to A, to duplicate in B's table where a's id is equal to b's id. -
writable nested model serializer requires manual parsing of request.data
After a lot of trouble I finally got a Django writable nested model serializer working using drf-writable-nested, for nested data with a reverse foreign key relationship. Currently this requires me to copy and manually parse request.data for all fields to create a new object before sending it to my serializer. If I don't do this I get the following (prints of serializer.data and errors respectively): serializer.data { "leerling": "2", "omschrijving": "Basispakket", "betaaltermijn": "14 dagen", "is_credit": false, "tegoeden": [ { "[aantal]": "1", "[prijs]": "450", "[btw_tarief]": "9%" }, { "[aantal]": "1", "[prijs]": "45", "[btw_tarief]": "21%" } ] } serializer.errors { "tegoeden": [ { "btw_tarief": [ "This field is required." ] }, { "btw_tarief": [ "This field is required." ] } ] } Some fields don't error because they are not required/have a default value. I tried manually declaring the JSON without brackets as input for the serializer, and then it works. So the problem is caused by the brackets. Its working now, manually parsing the request.data Querydict, but it feels hacky and probably not how it's supposed to be done. I'm probably missing something. -
Invalid block tag on line 7: 'render_meta'. Did you forget to register or load this tag?
models and template codes are here: models.py from django.db import models from meta.models import ModelMeta ... class Tool(ModelMeta,models.Model): title = models.CharField(max_length = 250,help_text='Title') photo = ResizedImageField(size=[250, 225]) description = RichTextUploadingField(blank=True) _metadata = { 'title': 'get_title', 'description': 'get_description', 'image': 'get_image', } def get_title(self): return self.title def get_description(self): return self.description[:150] def get_image(self): if self.photo: return self.photo.url return None html file is: {% load meta %} <!DOCTYPE html> <html lang="en" > <head> {% render_meta %} </head> <body> ok </body> </html> but i get this error: Invalid block tag on line 7: 'render_meta'. Did you forget to register or load this tag? I use Django==4.2 and django-meta==2.5.0. -
Django/Apache/mod_wsgi Deployment Issue: Internal Server Error & Redirect Loop on cPanel (AlmaLinux 9)
I'm an intern trying to deploy a Django application on a cPanel server, and I've run into a persistent "Internal Server Error" coupled with an Apache redirect loop. I've been troubleshooting for over two days with various AI helpers, but I can't pinpoint the exact cause. Any fresh perspectives ?? My Setup: Server OS : AlmaLinux 9.6 (Sage Margay) Hosting Environment: cPanel (My cPanel account does not have the "Setup Python App" option, which is why I'm using a manual Apache/mod_wsgi configuration.) Django Deployment: Apache + mod_wsgi No .htaccess content at all. Project Structure: I have two Django instances (production and staging) for CI/CD, each with its own settings, environment variables, database, and domain. validator/settings/base.py validator/settings/production.py (inherits from base) validator/settings/staging.py (inherits from base) Environment files are stored in /etc/validator/envs WSGI files are stored in /etc/validator/wsgi/ Django project roots: /home/<username>/<app_name>/ (prod) and /home/<username>/<app_name_test>/ (staging). Python Version: My virtual environments are running Python 3.12.9, and my WSGI files assert this. The Problem: When I try to access either domain.in (production) or test.domain.in (staging), I receive an "Internal Server Error". My Apache error log (specifically /var/log/httpd/error_log) shows the following critical error message: [Fri May 30 00:26:38.624027 2025] [core:error] [pid 253617:tid 253705] [client 45.115.89.80:26970] … -
Getting Attribute error in django BaseCommand- Check
I am working on a tutorial project. The same code works for the instructor but doesn't work for me. I have a file for custom commands: from psycopg2 import OperationalError as Psycopg2OpError from django.db.utils import OperationalError from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): def handle(self, *args, **options): self.stdout.write('waiting for database...') db_up = False while db_up is False: try: self.check(databases=['default']) db_up = True except(Psycopg2OpError, OperationalError): self.stdout.write("Database unavailable, waiting 1 second...") time.sleep(1) self.stdout.write(self.style.SUCCESS('Database available!')) And I am writing test case for the same in a file called test_command.py which is below: from unittest.mock import patch from psycopg2 import OperationalError as Psycopg2OpError from django.core.management import call_command from django.db.utils import OperationalError from django.test import SimpleTestCase @patch('core.management.commands.wait_for_db.Command.Check') class CommandTests(SimpleTestCase): def test_wait_for_db_ready(self, patched_check): """test waiting for db if db ready""" patched_check.return_value = True call_command('wait_for_db') patched_check.assert_called_once_with(databases=['default']) @patch('time.sleep') def test_wait_for_db_delay(self, patched_sleep, patched_check): """test waiting for db when getting operational error""" patched_check.side_effect = [Psycopg2OpError] * 2 + \ [OperationalError] * 3 + [True] call_command('wait_for_db') self.assertEqual(patched_check.call_count, 6) patched_check.assert_called_with(databases=['default']) When I run the tests, I get an error message- AttributeError: <class 'core.management.commands.wait_for_db.Command'> does not have the attribute 'Check' I am unable to resolve the error. The structure of the files are added below: ![Project Structure Here] (https://ibb.co/R44Swzs0) -
How to reduce latency in translating the speech to text (real time) in a Django-React project?
I have implemented a speech to text translation in my django-react project. I am capturing the audio using the Web Audio API, ie, using navigator.mediaDevices.getUserMedia to access the microphone, AudioContext to create a processing pipeline, MediaStreamAudioSourceNode to input the audio stream, AudioWorkletNode to process chunks into Float32Array data, and AnalyserNode for VAD-based segmentation.processes it into 16-bit PCM-compatible segments, and streams it to the Django backend via web socket. The backend, implemented in consumers.py as an AudioConsumer (an AsyncWebsocketConsumer), receives audio segments or batches from the frontend via WebSocket, intelligently queues them using a ServerSideQueueManager for immediate or batched processing based on duration and energy, and processes them using the Gemini API (Gemini-2.0-flash-001) for transcription and translation into English. Audio data is converted to WAV format, sent to the Gemini API for processing, and the resulting transcription/translation is broadcast to connected clients in the Zoom meeting room group. The system optimizes performance with configurable batching (e.g., max batch size of 3, 3-second wait time) and handles errors with retries and logging. Now there is a latency in displaying the translated text in the frontend. There is an intial delay of 10s inorder to display the first translated text. Subsequent text will … -
How to change the breakpoint at which changelist table becomes stacked?
In Unfold admin, the changelist table switches to a stacked layout on small screens — likely due to Tailwind classes like block and lg:table. I’d like to change the breakpoint at which this layout switch happens (for example, use md instead of lg, or disable it entirely to keep horizontal scrolling). How can this behavior be customized or overridden cleanly? -
How to find and join active Django communities for learning and collaboration?
How can I actively engage with the Django community? Looking for forums, Discord/Slack groups, or events to discuss best practices, ask questions, and contribute. Any recommendations? I want to connect with the Django community for learning and collaboration. I checked the official Django forum but couldn't find active discussions. What I tried: Searching Meetup.com for local Django groups (none in my area) Browsing Reddit's r/django (mostly news, not interactive) What I expect: Active Discord/Slack channels for real time help Local study groups or hackathons Contribution opportunities for beginners Any recommendations beyond official docs? -
How to use login_not_required with class-based views
Django 5.1 introduced the LoginRequiredMiddleware. This comes with the companion decorator login_not_required() for function-based views that don't need authentication. What do I do for a class-based view that doesn't need authentication? -
Django SSL error during send_mail() while explicitly using TLS
I'm trying to perform a send_mail() call in my Django application, but the mails are not sending. Checking the logs, I see the following error: [Thu May 29 09:35:20.097725 2025] [wsgi:error] [pid 793757:tid 140153008285440] [remote {ip.ad.dr.ess}:65062] Error sending email: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate (_ssl.c:1147) My smtp relay uses TLS w/ whitelisting, not SSL, and I've reflected that in my /project/settings/base.py file by setting EMAIL_USE_TLS = True. I've checked my certificate and it's up-to-date and my website's HTTPS is functional. I don't understand where the disconnect lies - why could an SSL error be preventing my email from sending when I'm using TLS?