Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-allauth stuck on signup and headless=True confusion
I'm trying to setup django-allauth app to be used for authentication by a front end react app and a mobile app. There are some inconsistencies which most likely are just down to me not figuring out something. But ton's of googling and AI ain't helping. I've done the setup (several times) as per the tutorial and using postman and I'm able to call /auth/login successfully for a user that had been created using createsuperuser My confusion/uncertainty starts when I try signup a new user via /auth/signup. It is "sort off" successful. I say sort of because the user does get created in the DB but I do not receive the email asking the user to Confirm Their Email. When I however try register the same email/user again, I now get an email saying [example.com] Account Already Exists. So I do know email delivery (using mailhog) is working. Here are my allaluth settings: HEADLESS_ONLY = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_LOGIN_METHODS = { "email", } ACCOUNT_SIGNUP_FIELDS = ["email*", "password1*",] ACCOUNT_SIGNUP_FORM_CLASS = "authy.forms.CustomSignupForm" ACCOUNT_EMAIL_VERIFICATION = "mandatory" # Ensures users must verify their email ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None # or a url ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = None # or a url ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 3 … -
Signals with Channels updating one value at the time
I'm using a m2m signal that triggers django channels, to create a realtime update on a value. It works fine but if I go to the admin and update more than one at the same time (having multiple tabs opened) it only updates 1 tab in real time and the others I need to refresh that. Does anyone know why it behaves like this? -
Deployed Django Rest Framework API gives "Server got itself in trouble" on any call with payload
I am deploying my Django Rest API to a web server running on Ubuntu 24.04 LTS Linux and using the Apache web server. This web server is external; I have not set it up, and so some of the details on how it works is a blackbox to me. I have run into a very annoying error in which I will get a 500 error saying "Server got itself in trouble" whenever I add payload to any sort of request. It doesn't matter the method: it can be a GET, POST, PUT, PATCH or DELETE and it will still run into the error... However, when I run a request without a payload, I don't run into this error (I run into expected errors for not including expected request data instead)... Here are some details on the server, that could give insight: The app runs within a Gunicorn container Client requests go to a reverse proxy and they are redirected to the app The app handles incoming requests and is listening out for them Here is also the settings.py I am using. I have DEBUG=True for now to try to get to the root of the issue... """ Django settings for … -
Error making django-oauth-toolkit migrations with add_token_checksum
I have a Django application that has been running for quite some time and I want to update the django-oauth-toolkit library. In this case the upgrade would be from version 2.4.0 to 3.0.1. The problem is that when I run the command python manage.py migrate the field of oauth2_provider.00XX_add_token_checksum is never set to OK, it stays processing and never stops. What the console shows me is the following: Operations to perform: Apply all migrations: admin, auth, contenttypes, oauth2_provider, sessions, users Running migrations: Applying oauth2_provider.0011_refreshtoken_token_family... OK Applying oauth2_provider.0012_add_token_checksum... What could it be? -
Cannot connect to websocket
I have app on Django Channels that use Daphne as a termination server and hosted on AWS EC2. So problem is, when i run app locally(or via ngrok) and try to connect everything is working, i have connection with websocket. But if i try to connect not locally, i get this: 17-03-2025 18:57:13 | django.request | WARNING | Not Found: /ws/chat/ 17-03-2025 18:57:13 | gunicorn.access | INFO | "GET /ws/chat/?first_user=19628&second_user=19629 HTTP/1.1" 404 179 routing.py from django.urls import path from apps.chat.consumers.consumers import ChatConsumer websocket_urlpatterns = [ path('ws/chat/', ChatConsumer.as_asgi()), ] asgi.py import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'settings.main') django.setup() from channels.auth import AuthMiddlewareStack # noqa: E402 from channels.routing import ProtocolTypeRouter # noqa: E402 from channels.routing import URLRouter # noqa: E402 from django.core.asgi import get_asgi_application # noqa: E402 from apps.chat.middlwares.queryparams import QueryParamsMiddleware # noqa: E402 from apps.chat.routing import websocket_urlpatterns # noqa: E402 application = ProtocolTypeRouter( { 'http': get_asgi_application(), 'websocket': AuthMiddlewareStack(QueryParamsMiddleware(URLRouter(websocket_urlpatterns))), } ) settings.py ASGI_APPLICATION = 'apps.asgi.application' INSTALLED_APPS += [ # Third-party apps 'daphne' 'django.contrib.admin', 'django.contrib.auth', ... 'channels', # Local apps ... 'apps.chat.apps.ChatConfig', ] CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { 'hosts': [os.environ.get('REDIS_URL', ('127.0.0.1', 6379))], }, }, } docker-compose.yml volumes: pg_data: driver: local x-base: &base-backend build: . volumes: - .:/code depends_on: - db … -
Template does not exists error in python anywhere
I have deployed my django app in python anywhere and getting below error : TemplateDoesNotExist at /topic/ cms_app\content.html I have two apps in my project. One is cms_app and other is users. My templates location is Content_Mgmnt/cms_app/templates /cms_app/content.html For users and other cms_app templates are working fine however for /topic/ url this is not working and showing templates does not exists. The same code is working fine in development environment however giving issues in production. How to solve this error? -
Twilio TTS Mispronounces "Aradhya" – How to Fix It?
I’m using Twilio's text-to-speech (TTS) in a Django view to read out a message before connecting a call. However, Twilio mispronounces the name "Aradhya", and I’m looking for a way to fix it. Problem: Twilio reads "Aradhya" incorrectly, and I want it to sound like "Uh-raa-dhyaa" (अाराध्य in Hindi). Code (Simplified Version): from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from twilio.twiml.voice_response import VoiceResponse @csrf_exempt def connect_call(request): response = VoiceResponse() customer_name = "John Doe" # Example; this is fetched dynamically in actual code response.say(f"Hello {customer_name}, I am Aradhya. Please hold while we connect you.") response.dial("+919836731154") # Connect call return HttpResponse(str(response), content_type="application/xml") What I Tried: Changing the spelling (e.g., "Aaraadhyaa", "Aradyaa") → No improvement. Using SSML <phoneme> tag: <Response> <Say> I am <phoneme alphabet="ipa" ph="əˈrɑːðjə">Aradhya</phoneme>. </Say> </Response> Issue: Twilio still mispronounces it. Adding pauses with <break>: <Say>Hello, I am <break time="200ms"/> Aaraadhyaa.</Say> Issue: Slight improvement, but not perfect. Using Twilio Neural Voices (Amazon Polly): <Response> <Say voice="Polly.Aditi">Hello, I am Aradhya.</Say> </Response> Issue: Not all Twilio accounts support Polly voices. Question: How can I get Twilio TTS to pronounce "Aradhya" correctly without using pre-recorded audio? Any help would be appreciated! -
Invalid Argument: X-Amz-Security-Token when my django-based website hosted by vercel tries to get static files from cloudflare r2
First of all: I have a R2 bucket on cloudflare that is public, allows any origins and any headers, and works completely fine. I'm using django-storages to storage and retrieve static files from that bucket, it works completely fine with the collectstatic command and is configured like so: CLOUDFLARE_R2_CONFIG_OPTIONS = { "bucket_name": os.getenv('AWS_STORAGE_BUCKET_NAME'), "default_acl": "public-read", "signature_version": "s3v4", "endpoint_url": os.getenv('AWS_S3_ENDPOINT_URL'), "access_key": os.getenv('AWS_S3_ACCESS_KEY_ID'), "secret_key": os.getenv('AWS_S3_SECRET_ACCESS_KEY'), } STORAGES = { "default": { "BACKEND": "storages.backends.s3.S3Storage", "OPTIONS": CLOUDFLARE_R2_CONFIG_OPTIONS, }, "staticfiles": { "BACKEND": "storages.backends.s3.S3Storage", "OPTIONS": CLOUDFLARE_R2_CONFIG_OPTIONS, }, } All the env variables are correct both in my local file and in my Vercel project settings. The problem is: When I try to get my static files running the server locally, I can get it without any issue. But when my hosted website tries to get it, it returns Invalid Argument: X-Amz-Security-Token . My console presents the following logs: A resource is blocked by OpaqueResponseBlocking, please check browser console for details. Loading failed for the <script> with source “https://0f69b46e85805ed2f43733e43b3c9d42.r2.cloudflarestorage.com/red-lily-art/static/teste.js?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=fc2577758bc2bd91c1e1022852b8e3cb%2F20250317%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20250317T130205Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Security-Token=IQoJb3JpZ2luX2VjEO3%2F%2F%2F%2F%2F%2F%2F%2F%2F%2FwEaCXVzLWVhc3QtMSJGMEQCIFvc%2F5JClCQ8o%2FGX8RNXEpe0LMctOAwwo0qN6YdtYmwAAiAdQ1vNe2ZdGRCy4bwIfvTe8CFy%2ByM7ZFu1O%2BeXdmJd3CrVAwhGEAMaDDY5MzU2ODkzNTA0MSIMzXoCS2fBSfvwBKTXKrIDl2MbDq6bezh5eKOXhGJuszK20Yqy3PgXmFdu945fK2RY8qPAvmxgHGPIhr2gi4wz0e4lOYiWHDzptMCBM%2FdISRQW2Yl6J7UIpQ0m1tE9%2FKLrC30JOVj1uPOtDyNrxF5TMGAuzX6%2FPaj6rezUdIa2AzT7cf3v1w%2BrQg781axTRL07H02ZHcJteVyFWclCth%2FrLvWPgHLxU3jgOTTxkpVycib%2F%2BcA0QTrU58x2pedmC5JfMI10fekZS1ZjBWprA9bDN3csTw6cyo6TICcbTMqH9i5xu2xRDIt6yDr6GS0876VDITy57qC5AdXX71Cgd7YdmgEYSmWFTSEYklJfsnjzHMqX7KtahskM%2BjTyrfHhtJ85NEWXfuxfUdR0d5jaN72K%2B6qbsYbopUjty7CJyo%2FwgjS7BF4P66gQNFBALc9d1R%2F92B%2BPvvpyXiD5j58ZJ5oC65W%2BlOGW96QPTCwO9b5M0ppmmO7K887wq5uVmGqZPoy7dymflBOsiAiDYYNYdyTfskRus7utsEYr0UMldBqKkheBRthKTr%2FIMtgdDGFS7YPPcE99Gu%2B%2FvO1diPH3pHlw3iEwyrrgvgY6nwHHzJTW6CRoh3VBIOe6GsNTop8DsRliEZK4jyOvn%2Btzk%2BEAvSQyfnVI7TSJIDyw%2FcV1S5OZq%2Fw%2Fd6U%2Fnuvjiyxto%2FvYXVhKxJumc4TpEQ3XqlX11hckBvSngjB6EUGL%2FjVI%2BxpgWnNx7HmU4xSct2pnfoOa3fYj8HvhZ58hH2K8T3vdm1gQ%2FIesyfMgy8TIrwMiXlgf29RIQ2MsTE8f16U%3D&X-Amz-Signature=a33b4d6841de2678820682bd4337a2c04ddc65fcb09646cafe8804530df4d31d”. -
la commande makemigrations pools
I got stuck at the second step of the tutorial at docs.djangoproject.com/fr/5.1/intro/tutorial02/. When I run the makemigrations polls command, the result is: PS C:\Users\user\desktop\djangotutorial> python manage.py makemigrations polls Traceback (most recent call last): File "C:\Users\user\desktop\djangotutorial\manage.py", line 22, in <module> main() ~~~~^^ File "C:\Users\user\desktop\djangotutorial\manage.py", line 18, in main execute_from_command_line(sys.argv) ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python313\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() ~~~~~~~~~~~~~~~^^ File "C:\Users\user\AppData\Local\Programs\Python\Python313\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() ~~~~~~~~~~~~^^ File "C:\Users\user\AppData\Local\Programs\Python\Python313\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\user\AppData\Local\Programs\Python\Python313\Lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\user\AppData\Local\Programs\Python\Python313\Lib\site-packages\django\apps\config.py", line 190, in create raise ImportError(msg) ImportError: I don't understand where the problem is coming from. I tried to go through the settings.INSTALLED_APPS settings under the microscope without success. I need your help. -
I don't really know how to phrase this but I'm currently using Django, that is being picked up through my vs code but its not registering my apps
INSTALLED_APPS = [ # MY APPS: "learning_logs", # DEFAULT APPS: 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] My teacher has helped me, we even turned to AI, but nothing is working. For example, my teachers code runs perfectly on his side, and he even gave me his code however mine is still not working. So, we think 'MY APPS' is not being picked up on. Btw this is from my settings.py So, after changing code and even using his it's not working. Every time I run my server and follow the link it takes me to the default Django home page when it's supposed to give me my web page. I hope this makes sense, I've been struggling with this problem for 3 days. -
Django MultiValueDictKeyError: 'category' When Submitting Form
'm working on a Django To-Do app, and I'm trying to implement an edit feature where users can modify a task's category and importancy. I have an edit.html template that contains a form, and when I submit it, I get the following error: django.utils.MultiValueDictKeyError: 'category' Code Details edit.html (Template with Form) {% block content %} <h2>Edit Task</h2> <form action="{% url 'todo:edit' task.id %}" method="post"> {% csrf_token %} <input type="text" name="category" value="{{ task.category }}" /> <input type="text" name="importancy" value="{{ task.importancy }}" /> <input type="submit" value="Edit"> </form> {% endblock content %} views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import Task def edit(request, task_id): task = get_object_or_404(Task, id=task_id) if request.method == 'POST': print(request.POST) # Debugging to check form data task.category = request.POST['category'] # This line causes the error task.importancy = request.POST['importancy'] task.save() return redirect('todo:index') return render(request, 'todo/edit.html', {'task': task}) I checked my form to make sure the name="category" is correct, and it matches what I’m trying to access in request.POST. Double-checked the form method to ensure it's POST and not GET. Looked at my URLs to see if anything there could be interfering, but it seems fine. -
Is It Reasonable to Simplify Product Variant Design Using Notes Instead of Complex Relations?
I'm building an application where product variants are intended to be handled as physical products already prepared and listed manually. Instead of using a conventional approach with complex relations between Product, Option, OptionValue, and SKUValue tables, I'm trying to simplify the design. 💡 ERD Design: +--------------+ +-----------------+ | Product | | ProductVariant | +--------------+ +-----------------+ | id (PK) |<------>| id (PK) | | name | | product_id (FK) | | owner_id (FK)| | note | | created_at | | stock | | updated_at | | price | +--------------+ +-----------------+ In the ProductVariant table, the note field is a simple text field where users can manually enter descriptions like "Size: XL, Color: Red". 🔍 Django Models Based on This Design: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Product(models.Model): name = models.CharField(max_length=255) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='products') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class ProductVariant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='variants') note = models.TextField() # Example: "Size: XL, Color: Red" stock = models.PositiveIntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return f"{self.product.name} - {self.note}" 🎯 Why I'm Doing This: The application is designed to handle product variants that are often predefined and don't change dynamically. … -
How do I specify directories Tailwindcss v4 should scan for class names?
I currently have a django application structured like this: /project-root | | /shop # installed application | ├── templates/ # Django templates directory (HTML files) │ ├── base.html │ ├── index.html │ ├── other_template.html │ └── ... ├── static/ │ └── shop/ │ ├── styles/ # Tailwind CSS setup lives here │ │ ├── node_modules/ # Installed NPM packages (Tailwind, etc.) │ │ ├── src/ # Source files for Tailwind │ │ │ ├── input.css │ │ ├── dist/ # Output folder (compiled Tailwind CSS) │ │ │ ├── output.css # Compiled Tailwind CSS │ │ ├── tailwind.config.js │ │ ├── package.json # Dependencies │ │ ├── package-lock.json # Dependency lock file │ ├── js/ # JavaScript files (if any) │ │ ├── main.js │ │ ├── other_script.js │ │ └── ... └-- views.py ---- models.py // other files The problem is I noticed when running the command npx tailwindcss -i ./src/input.css -o ./dist/output.css --watch Tailwindcss only scans html files in the styles directory. I tried moving the node_modules and package.json to the root folder but it still wasn't able to pick up any of the html files in the templates folder. I tried creating a tailwind.config.js in the styles … -
Django Static Files Not Loading in Production (DEBUG=False) with Gunicorn on Kubernetes
Problem I'm running a Django application in a Kubernetes pod with Gunicorn, and my static files (admin panel CSS/JS) are not loading when DEBUG=False. In local development, I use runserver, and everything works fine with DEBUG=True. However, when I set DEBUG=False, my static files return 404. Error Logs (Browser Console / Django Logs) GET /static/admin/css/base.efb520c4bb7c.css HTTP/1.1" 404 179 GET /static/admin/js/nav_sidebar.7605597ddf52.js HTTP/1.1" 404 179 Relevant Django Settings (settings.py) DEBUG = False INSTALLED_APPS = [ "django.contrib.staticfiles", # Other apps... ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # Other middleware... ] BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" STATICFILES_DIRS = [ BASE_DIR / 'static', ] STATIC_ROOT = BASE_DIR / 'staticfiles' How I Run My App (Docker Entrypoint) #!/bin/sh APP_PORT=${PORT:-8000} echo "Migrating database..." /opt/venv/bin/python manage.py migrate --noinput echo "Collecting static files..." /opt/venv/bin/python manage.py collectstatic --noinput echo "Static files collected" echo "Starting server..." /opt/venv/bin/gunicorn secureuri.wsgi:application --bind "0.0.0.0:${APP_PORT}" --workers 1 --access-logfile - --error-logfile - --log-level debug What I Tried Checked that collectstatic is running. Running ls -la staticfiles/admin/css/ shows that files exist inside the container. Tried running Django’s built-in dev server with DEBUG=False Running python manage.py runserver --insecure does not work Checked Gunicorn Logs Gunicorn is running fine, and there are no errors related to … -
djLint is not installed for the current active Python interpreter – How to Make djLint Available in All Virtual Environments in VS Code?
I have installed the djLint extension in VS Code and updated my settings file. ... "[html][django-html][handlebars][hbs][mustache][jinja][jinja-html][nj][njk][nunjucks][twig]": { "editor.defaultFormatter": "monosans.djlint" }, "[django-html]": { "editor.defaultFormatter": "monosans.djlint", "editor.detectIndentation": true, "editor.formatOnSave": true, "editor.tabSize": 4, "djlint.profile": "django" // This will apply your custom profile }, ... However, when I create a new directory and set up a virtual environment (.venv), I get the following error when trying to save a Django template: djLint is not installed for the current active Python interpreter. Install it with the `c:\Test\Django\Test\.venv\Scripts\python -m pip install -U djlint` command. I want to avoid manually installing djLint in every virtual environment. Would appreciate any solutions or best practices. Thanks! -
Intermittent server error in Django after upgrading to MySQL 8
After upgrading to MySQL 8 and keeping everything else the same in a Django project I'm getting an intermittent server error which seems to be something to do with a package called cookiebanner that I've been using without problems for a couple of years -- https://github.com/sinnwerkstatt/django-cookiebanner New here -- hello -- hope I'm posting this in the right place. And hope there's the right info here for this topic to be useful. 2025-03-08 05:48:19,903: KeyError: 'request' 2025-03-08 05:48:19,903: File "XXX/lib/python3.8/site-packages/django/core/handlers/wsgi.py", line 133, in __call__ 2025-03-08 05:48:19,904: response = self.get_response(request) 2025-03-08 05:48:19,904: 2025-03-08 05:48:19,904: File "XXX/lib/python3.8/site-packages/django/core/handlers/base.py", line 130, in get_response 2025-03-08 05:48:19,904: response = self._middleware_chain(request) 2025-03-08 05:48:19,905: 2025-03-08 05:48:19,905: File "XXX/lib/python3.8/site-packages/django/core/handlers/exception.py", line 49, in inner 2025-03-08 05:48:19,905: response = response_for_exception(request, exc) 2025-03-08 05:48:19,905: 2025-03-08 05:48:19,905: File "XXX/lib/python3.8/site-packages/django/core/handlers/exception.py", line 114, in response_for_exception 2025-03-08 05:48:19,905: response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) 2025-03-08 05:48:19,905: 2025-03-08 05:48:19,905: File "XXX/lib/python3.8/site-packages/django/core/handlers/exception.py", line 153, in handle_uncaught_exception 2025-03-08 05:48:19,905: return callback(request) 2025-03-08 05:48:19,906: 2025-03-08 05:48:19,906: File "XXX/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view 2025-03-08 05:48:19,906: response = view_func(request, *args, **kwargs) 2025-03-08 05:48:19,906: 2025-03-08 05:48:19,906: File "XXX/lib/python3.8/site-packages/django/views/defaults.py", line 97, in server_error 2025-03-08 05:48:19,906: return HttpResponseServerError(template.render()) 2025-03-08 05:48:19,906: 2025-03-08 05:48:19,906: File "XXX/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render 2025-03-08 05:48:19,906: return self.template.render(context) 2025-03-08 05:48:19,906: 2025-03-08 05:48:19,906: … -
Multiple different attachments using Gmail API in Django
How do we account for sending multiple (or no) attachments (via request.FILES) in Django using the Gmail API, so we can store the legacy message ID (ie "FBf…MiD") for future retrieval to reply in the same thread/thread_ID? I am switching from the SMTP (to be fully deprecated by Google) of Django's email.send(), which appears to be significantly different in how it handles file types. I am specifically struggling to find out how to attach multiple files of different types to the Gmail API. view.py class MakeQuoteWithItems(…, CreateView): def post(self, request, *args, **kwargs): # init a Django Model quote = QuoteClass(request) # with a generated PDF, and send the associated email quote.make_and_email_quote() Current working way (SMTP) from django.core.mail import EmailMultiAlternatives def emailContactsTheOptionsQuote(quote, attachments=None): from_email = … subject = … email_context = … html_content = render_to_string("email/tempalte.html", email_context, quote.request) to_emails = … (string, [] or whatever format needed) … # # Current working way sending through SMTP # # Django settings somehow gets the email out # EMAIL_USE_TLS = False # EMAIL_HOST = os.getenv("EMAIL_PROVIDER_SMTP_NOTIFIER_HOST") # EMAIL_HOST_USER = os.getenv("EMAIL_PROVIDER_SMTP_NOTIFIER_EMAIL") # EMAIL_HOST_PASSWORD = os.getenv("EMAIL_PROVIDER_SMTP_NOTIFIER_PASSWORD") # EMAIL_PORT = 587 # mail = EmailMultiAlternatives( subject, strip_tags(html_content), to=to_emails, bcc=bcc_emails, from_email=from_email, ) mail.attach_alternative(html_content, "text/html") mail.attach( quote.pdf_canvas._filename, open(quote.canvas._filename, "rb").read(), "application/pdf" … -
How can I change the success url of allauth AddEmailForm?
I have a UserDetail page that includes several forms. from allauth.account.forms import ChangePasswordForm, AddEmailForm User = get_user_model() class UserDetailView(LoginRequiredMixin, DetailView): model = User slug_field = "username" slug_url_kwarg = "username" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # context["form_info_username"] = context["form_add_mail"] = AddEmailForm(user=self.request.user) context["form_change_password"] = ChangePasswordForm(user=self.request.user) return context When I add a new email: <form method="post" action="{% url 'account_email' %}" class="add_email mt-2"> {% csrf_token %} {{ form_add_mail|crispy }} <div class="flex justify-end mt-2"> <button type="submit" name="action_add" class="bg-green-600 hover:bg-green-800 dark:bg-green-600 dark:hover:bg-green-800 font-semibold text-white rounded-sm p-2 text-xs sm:text-sm sm:px-8 "> {% translate "Add E-mail" %} </button> </div> </form> The form/view({% url 'account_email' %}) redirects to http://localhost:8000/de/accounts/email/, but I would prefer it to refresh the same page instead. -
Issue with Saving Dynamic Formset Data on Frontend: Event Dates and Times Not Persisting
I’m facing an issue where dynamic formsets (for event dates and times) on the frontend are not saving correctly. The form is properly rendered, and new event dates and times are added dynamically using Alpine.js, but when the form is submitted, the data does not persist. This issue does not occur in the Django admin interface, where formsets work fine. I suspect the problem is related to how the formset data is being processed on the frontend. I’m using Django with Alpine.js for formset handling, and I’m looking for help in resolving the issue of saving the dynamic formset data on the frontend. this is my models class EventOption(models.Model): name = models.CharField(_("Option name"), max_length=100) amount = models.DecimalField(_("Price"), max_digits=10, decimal_places=2) slug = AutoSlugField(populate_from='name', unique=True) published = models.DateTimeField(auto_now_add=True) class Meta: verbose_name = _("Event Option") verbose_name_plural = _("Event Options") def __str__(self): return f"{self.name} - {self.amount}TND" class Event(models.Model): name = models.CharField(_("Event name"), max_length=100) slug = AutoSlugField(populate_from='name', unique=True) published = models.DateTimeField(auto_now_add=True) options = models.ManyToManyField( EventOption, verbose_name=_("Event Options"), blank=True) amount = models.DecimalField(_("Price"), max_digits=10, decimal_places=2) description = models.TextField(_("Description"), blank=True, null=True) class Meta: verbose_name = _("Event") verbose_name_plural = _("Events") def __str__(self): return self.name class EventDate(models.Model): event = models.ForeignKey( Event, on_delete=models.CASCADE, related_name='event_dates') date = models.DateField(_("Event date")) class Meta: verbose_name … -
Tailwindcss v4 Grid columns
I'm putting together a blog in Django(v4x) and trying to use TailwindCSS v4 to list out the blog posts in a column template, 3 across. They list out 3, going down, not across, what am I doing wrong? Here is what I have in my blog index.html Django html template {% block content %} <div class="border-8 border-purple-900"> <h1>Articles</h1> <div class="grid grid-cols-3 gap-4"> <div>01</div> <div>02</div> <div>03</div> <div>04</div> <div>05</div> <div>06</div> <div>07</div> <div>08</div> <div>09</div> </div> {% for post in posts %} <div class="grid grid-cols-3 gap-1"> <div class="border-4 border-black"> <article> <h1 class="text-2xl font-semibold"> <a href="{% url 'blog:blog_detail' post.slug %}">{{ post.title }}</a> </h1> <h4>{{ post.created_at.date }}</h4> <!-- <p>{{ post.author }}</p> --> <div>{{ post.content | slice:":50" }}...</div> </article> </div> </div> {% endfor %} </div> {% endblock %} I even copy+pasted the html from Tailwind docs page and it seems like it should work. What am I doing wrong? -
Django form label changes
I want to change a label on a form on a django profile it's for a profile page on a new django project. is used co-pilot to edit this but the changes didn't work. So I need a quick fix if possible? I hope that somebody can help with this as soon as possible. -
How can I solve the Error in setup django project
[After giving runserver command][errors] when i try to run the project or want to migrate then the error is occuring.virtual environment is activated and all dependencies are installed. -
how to delete delete OneToOneField of a model class in django
in my django app student_management_system, Student is connected to User by OneToOneField. if i delete a Student it gets deleted, but User (django's built in User) is not getting deleted, it still exists in database, ie. in auth_user of db.sqlite3. how to fix this. github code: https://github.com/anup30/student_management_system the problem is also written in problem.txt there. -
How to retrieve singleton model instance with DRF without having to provide id?
I have a django app, and I use django-solo for SingletonModel. I do have a singleton settings model: class GeneralSettings(SingletonModel): allow_signup = models.BooleanField(default=True) I want to create an API endpoint to be able to retrieve and update the settings. I currently use DRF. Using RetrieveModelMixin and UpdateModelMixin I can easily do it but then my route has to be: .../api/settings/1 < I need to add the id. How can I retrieve / update my settings without having to use the id (since it doesn't make sens for a SingletonModel)? DRF view: class GeneralSettingsViewSet( RetrieveModelMixin, UpdateModelMixin, GenericViewSet, ): queryset = GeneralSettings.objects.all() serializer_class = GeneralSettingsSerializer http_method_names = ["get", "put"] def get_object(self) -> GeneralSettings: return GeneralSettings.get_solo() Router: router.register(r"settings", GeneralSettingsViewSet, "api-settings") -
Should I reach into the Django _prefetched_objects_cache to solve an N+1 query?
I have the following Django template code with an N+1 query: {% for theobject in objs %} {% for part in theobject.parts_ordered %} <li>{{ part }}</li> {% endfor %} {% endfor %} Here is parts_ordered on TheObject: class TheObject: # ... def parts_ordered(self) -> list["Part"]: return self.parts.all().order_by("pk") And here is the Part object: class Part: # ... theobject = models.ForeignKey( TheObject, on_delete=models.CASCADE, related_name="parts" ) and here is the prefetch getting objs: ofs = ObjectFormSet( queryset=TheObject.objects .filter(objectset=os) .prefetch_related("parts") ) I think the order_by("pk") disrupts the prefetch. This is what chatgpt recommends, and it works (no more N+1 queries, results seem the same): class TheObject: # ... def parts_ordered(self) -> list["Part"]: if ( hasattr(self, "_prefetched_objects_cache") and "parts" in self._prefetched_objects_cache ): # Use prefetched data and sort in Python return sorted( self._prefetched_objects_cache["parts"], key=lambda cc: cc.pk ) # Fallback to querying the DB if prefetching wasn’t used return self.parts.all().order_by("pk") Should I rely on _prefetched_objects_cache? Is there a better way?