Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Error with ManyToManyField relation in Django
I am creating a kanban django model to my project, but i already tried a lot of things, i have read the django.docs, but i didn't find anything. ERRORS: tasks_management.Account.projects: (fields.E339) 'AccountProjects.owner' is not a foreign key to 'Project'. tasks_management.AccountProjects: (fields.E336) The model is used as an intermediate model by 'tasks_management.Account.projects', but it does not have a foreign key to 'Account' or 'Project'. from django.contrib.auth.models import User from django.db import models class Project(models.Model): project_name = models.CharField(max_length=50) def __str__(self): return self.project_name class Account(models.Model): username = models.CharField(max_length=50) email = models.EmailField(max_length=254) password = models.CharField(max_length=30) projects = models.ManyToManyField( Project, through='AccountProjects', through_fields=('contributors', 'owner'), blank=True ) def __str__(self): return self.username class AccountProjects(models.Model): owner = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='owner_project') contributors = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='contributors_project') # # class Board(models.Model): # project_name = models.ForeignKey(Project, on_delete=models.CASCADE) # # def __str__(self): # return self.project_name.project_name # # class Column(models.Model): # column_name = models.CharField(max_length=30) # board_name = models.ForeignKey(Board, on_delete=models.CASCADE) # order_position = models.IntegerField(default=1) # # def __str__(self): # return self.column_name # # class Task(models.Model): # task_name = models.CharField(max_length=50) # description = models.TextField() # creation_date = models.DateField(auto_created=True) # updated_date = models.DateField(auto_now=True) # column_name = models.ForeignKey(Column, on_delete=models.CASCADE) # # def __str__(self): # return self.task_name I read the docs, but i didn't find anything, the database requirements … -
bootstrap 5.3.3 how to remove the background containers?
Trying to figure out how to eliminate those background containers. Here is my code. I tried removing all the containers and cards but it still didn't eliminate it. I've looked in my base.html and it does not have any cards or containers. all it has is the nav bar. I've tried using p-0 but that just shifted everything to the left. {% extends "users/base.html" %} {% block title %} Register as Customer {% endblock title %} {% block content %} <div class="container mt-5"> <div class="row justify-content-center"> <div class="col-md-8"> <h4 class="text-center">Create Customer Account</h4> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {% if form.errors %} <div class="alert alert-danger alert-dismissible fade show" role="alert"> <div id="form_errors"> {% for key, value in form.errors.items %} <strong>{{ value }}</strong> {% endfor %} </div> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endif %} <div class="form-row"> <div class="col-md-6"> <div class="form-group"> <label class="small mb-1"><i class="fas fa-user"></i> First Name</label> {{ form.first_name }} </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="small mb-1"><i class="fas fa-user"></i> Last Name</label> {{ form.last_name }} </div> </div> </div> <div class="form-row"> <div class="col-md-6"> <div class="form-group"> <label class="small mb-1"><i class="fas fa-user"></i> Username</label> {{ form.username }} </div> </div> <div class="col-md-6"> <div class="form-group"> <label class="small mb-1"><i class="fas fa-envelope"></i> Email</label> {{ form.email }} </div> … -
Django `bulk_update()` : Update Different Fields for Each Record in a Single Query
I have two model instances, rec1 and rec2, but each has different fields updated: rec1 = MyModel(id=1, name="John") # Only 'name' is changed rec2 = MyModel(id=2, age=30) # Only 'age' is changed Now, I want to update both records efficiently using bulk_update(). However, bulk_update() requires a fixed list of fields, meaning: updated_fields = ['name', 'age'] model.objects.bulk_update([rec1, rec2], fields=updated_fields) This updates both fields in both records, even though: rec1 only needs to update name rec2 only needs to update age Goal: Update only the changed fields for each record in a single query. Avoid unnecessary updates to unchanged fields. Issue: bulk_update() applies the same field list to all records, leading to redundant updates. Question: Is there a way to update only the modified fields per record efficiently in a single query? Or is there an alternative approach to handle this in Django ORM? model.objects.bulk_update(instances_to_update, fields=updated_fields) where updated_fields is a list. i was expecting updated_fields as a iteration type function. -
column "now" does not exist postgres django
I have a django app that store a date column in a model/table in postgres first_subscribed = models.DateField(auto_now=True), and it works fine. But if I enable a trigger to copy data from the table/model to another table. I get : psycopg2.errors.UndefinedColumn: column "now" does not exist . The log from the server: flag4 2025-03-13T18:34:03.451065+00:00 app[web.1]: Internal Server Error: /subscriptions/stripe_webhook/ 2025-03-13T18:34:03.451067+00:00 app[web.1]: Traceback (most recent call last): 2025-03-13T18:34:03.451068+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/django/db/backends/utils.py", line 105, in _execute 2025-03-13T18:34:03.451068+00:00 app[web.1]: return self.cursor.execute(sql, params) 2025-03-13T18:34:03.451068+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2025-03-13T18:34:03.451068+00:00 app[web.1]: psycopg2.errors.UndefinedColumn: column "now" does not exist 2025-03-13T18:34:03.451069+00:00 app[web.1]: LINE 1: v_date_ini := now::date 2025-03-13T18:34:03.451069+00:00 app[web.1]: ^ 2025-03-13T18:34:03.451069+00:00 app[web.1]: QUERY: v_date_ini := now::date 2025-03-13T18:34:03.451070+00:00 app[web.1]: CONTEXT: PL/pgSQL function tg_fun_name() line 13 at assignment 2025-03-13T18:34:03.451071+00:00 app[web.1]: The above exception was the direct cause of the following exception: 2025-03-13T18:34:03.451071+00:00 app[web.1]: 2025-03-13T18:34:03.451071+00:00 app[web.1]: Traceback (most recent call last): 2025-03-13T18:34:03.451072+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner 2025-03-13T18:34:03.451072+00:00 app[web.1]: response = get_response(request) 2025-03-13T18:34:03.451072+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^^^ 2025-03-13T18:34:03.451073+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response 2025-03-13T18:34:03.451074+00:00 app[web.1]: response = wrapped_callback(request, *callback_args, **callback_kwargs) 2025-03-13T18:34:03.451074+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2025-03-13T18:34:03.451074+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/django/views/decorators/http.py", line 64, in inner 2025-03-13T18:34:03.451074+00:00 app[web.1]: return func(request, *args, **kwargs) 2025-03-13T18:34:03.451075+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2025-03-13T18:34:03.451075+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/django/views/decorators/csrf.py", line 65, in _view_wrapper 2025-03-13T18:34:03.451075+00:00 app[web.1]: return … -
Database Connections Spiking on Heroku Dyno Startup with django-db-geventpool – MAX_CONNS Not Enforced
I'm using Django, Gunicorn with Gevent, and django-db-geventpool on Heroku (Performance L dynos, WEB_CONCURRENCY=17). My database connections spike significantly on dyno startup, exceeding the expected number of connections. Expected Behavior Given my setup: MAX_CONNS=4 (per worker) REUSE_CONNS=2 WEB_CONCURRENCY=17 (workers per dyno) 6 dynos in production I would expect each dyno to hold at most 68 connections (17 workers * 4 MAX_CONNS). However, on startup, I see single dynos temporarily holding 150+ idle connections, which contributes to hitting Heroku’s 500 connection limit. Key Questions What does django-db-geventpool do if more than MAX_CONNS connections are requested? Are requests queued and forced to wait for a connection to free up? Or does django-db-geventpool ignore MAX_CONNS and allow connections to exceed the limit? Why might I be seeing connection spikes during dyno startup? Steps Taken So Far Verified that the spike happens only during startup, not under normal traffic. Checked pg_stat_activity and saw many idle connections from the same dyno. Ensured I’m not leaking connections from Celery, cron jobs, or background tasks. Has anyone encountered this issue with django-db-geventpool on Heroku? Any insights on whether it respects MAX_CONNS or if connections can exceed the limit under high concurrency? -
I have added a custom loggin to my django project but it isn't working
I have added this code to my settings.py, but its not working. Django defualt logging works perfectly fine, debug is True in my settings and i've created logs folder manually. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'file_logging': { 'format': '{levelname} / {levelno} - {asctime} --- {pathname} in {lineno} --- {process:d} {thread:d} -- {message}', 'style': '{' }, 'email_logging': { 'format': '{levelname} at {asctime} --- {pathname} in {lineno} -- {message}', 'style': '{' }, }, 'filters': { 'debug_true_required': { '()': 'django.utils.log.RequireDebugTrue' } }, 'handlers': { 'full_handler': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': 'logs/full.log', 'formatter': 'file_logging', }, 'critical_handler': { 'level': 'CRITICAL', 'class': 'logging.FileHandler', 'filename': 'logs/critical.log', 'formatter': 'file_logging', }, 'error_handler': { 'level': 'ERROR', 'filters': ['debug_true_required',], 'class': 'logging.FileHandler', 'filename': 'logs/error.log', 'formatter': 'file_logging', }, 'critical_email_handler': { 'level': 'CRITICAL', 'class': 'django.utils.log.AdminEmailHandler', 'formatter': 'email_logging', }, 'error_email_handler': { 'level': 'ERROR', 'filters': ['debug_true_required',], 'class': 'django.utils.log.AdminEmailHandler', 'formatter': 'email_logging', }, }, 'loggers': { 'file_logger': { 'handlers': ['full_handler', 'critical_handler', 'error_handler'], 'level': 'INFO', 'propagate': True }, 'email_logger': { 'handlers': ['critical_email_handler', 'error_email_handler'], 'level': 'ERROR', 'propagate': True }, } } I tried recreating logs folder again, but it didn't work, then i tried changing 'propagate': False to True but it didn't work again, and also i tried logging manualy with this code, which works … -
Choices field not rendering in HTML page in my Django project
I have a model with 3 Charfields with choices, I am struggling to render the choices in my html page. On the html page, I had a card color coded between 3 colors. Instead of rendering based on selected choice in the backend, it renders the same results across different vin searches. Here is the model in model.py class VehicleStatus(models.Model): """ Represents the status of a vehicle, including accident history, odometer fraud, and theft involvement. """ ACCIDENT_HISTORY = [ ("NHA","No History of Accidents"), ("OIIA", "Once Involved In Accident"), ("CAD", "Currently Accident Damaged"), ] ODOMETER_FRAUD = [ ("NOF", "No Odometer Fraud"), ("SOF", "Suspected Odometer Fraud"), ] THEFT_INVOLVEMENT = [ ("NHT", "No History of Theft"), ("OIT", "Once Involved In Theft"), ("STI", "Suspected Theft Involvement"), ] vin_number = models.OneToOneField(Vin, on_delete=models.CASCADE, related_name='vehiclestatus', db_index=True, help_text="Vehicle Identification Number") accident_history = models.CharField(max_length=30, choices=ACCIDENT_HISTORY, default='NHA', help_text="History of accidents involving the vehicle") odometer_fraud = models.CharField(max_length=30, choices=ODOMETER_FRAUD, default='NOF', help_text="Indicates if the vehicle has suspected odometer fraud") theft_involvement = models.CharField(max_length=30, choices=THEFT_INVOLVEMENT, default='NHT', help_text="Indicates if the vehicle has been involved in theft") owner_history = models.IntegerField(help_text="Number of previous owners of the vehicle", default=0) def __str__(self): return f"Vehicle Status for VIN {self.vin_number}" class Meta: verbose_name = "Vehicle Status" verbose_name_plural = "Vehicle Statuses" Here is …