Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django DisallowedHost: “Invalid HTTP_HOST header” despite correct ALLOWED_HOSTS and nginx configuration
I am running a Django 4.2.20 application on an Ubuntu server with Gunicorn and nginx as reverse proxy. However, I get the following error when I access the website via the public IP: Exception Type: DisallowedHost at / Exception Value: Invalid HTTP_HOST header: '89.168.121.242,89.168.121.242'. The domain name provided is not valid according to RFC 1034/1035. I have already checked the following: ALLOWED_HOSTS in settings.py: ALLOWED_HOSTS = ['ipaddress', 'localhost'] nginx configuration (/etc/nginx/sites-available/familyapp): server { listen 80; server_name ipaddress; location /static/ { alias /home/familyapp/FamilyApp/familyapp/static/; } location /media/ { alias /home/familyapp/FamilyApp/media/; } location / { include proxy_params; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://unix:/home/ubuntu/sockets/gunicorn.sock; } } nginx syntax check & restart sudo nginx -t # No errors sudo systemctl restart nginx sudo systemctl restart gunicorn Gunicorn started manually gunicorn --bind unix:/home/ubuntu/s -
Workflow for Angular/Django app development
I'm working on an app using Django & Angular. I need to build the Angular app and deploy it to be served through the Django dev server in order to use Django as the backend, and I'm wondering if there's a way to optimize the following steps: Building the Angular app with ng build Removing the Angular files from the static files directory in my Django app Copying the built Angular app to the Django app static files directory Ideally I'd like to have it done automatically on edit/save, similar to how each framework works independently. Do I have to cobble something together or is this supported already somehow? Thanks. -
Heroku installs extra Python package
I have a Python/Django app which uses Pipfile and Pipfile.lock running on Heroku-22 stack. requirements.txt is not part of the code base. Pipfile and Pipfile.lock contain psycopg2. Testing env has expected packages installed, however, production env has an extra package, psycopg, installed. $ heroku run bash -a my-app-production ~ $ pip freeze | grep -i psyco psycopg==3.2.4 psycopg2==2.9.10 vs $ heroku run bash -a my-app-testing ~ $ pip freeze | grep -i psyco psycopg2==2.9.10 Any idea where is this extra psycopg package coming from? -
How to find server_version in psycopg3?
I have this test in Django [1]: from django.db import connection def test_postgresql_version(self): postgresql_version = connection.cursor().connection.server_version if (postgresql_version >= 140000): pass else: raise NotImplementedError("postgresql version must be at least 14.0.") This test fails with psycopg3: AttributeError: 'Connection' object has no attribute 'server_version' How do I check the server_version in psycopg3? -
Django default_storage can`t find an existing file
I'm setting up work with my django app, but I ran into a problem when checking for any file in S3 storage. I can't figure out why I can't use the exists() method in my code. I searched for an error for a long time, but it turned out that the exists() method always returns False to me. Here is an example: >>> from django.core.files.storage import default_storage >>> print(default_storage.listdir("")) (['media', 'preview'], ['address_preview_1.png','address_preview_35.jpg']) >>> >>> print(default_storage.listdir("media")) ([], ['address_preview_35.jpg']) >>> print(default_storage.exists('address_preview_35.jpg')) False >>> print(default_storage.exists('/media/address_preview_35.jpg')) False >>> print(default_storage.exists('media/address_preview_35.jpg')) False >>> print(default_storage.location) media We see that the file "address_preview_35.jpg " there is both in the root of the repository and in the "media" folder. All arguments in settings.py are configured as described in the documentation. The image files are definitely on the server. We can open it. We can get the image from the full link. We can upload new files to the server and we can delete old ones. We can do everything EXCEPT check whether there is a file on the server or not. What am I doing wrong!? I tried accessing the server directly and via s3cmd. I tried accessing the repository in the module via from storages.backends.s3boto3 import S3Boto3Storage s3_storage … -
Docker-Compose Error When Building Django Dockerfile: Error -2 connecting to redis:6379. Name or service not known
I’m trying to set up an open-source status page application using the repository from Status-Page/Status-Page with Docker Compose. When I run docker-compose up -d, I encounter an error during the build process of the Django service’s Dockerfile. The error seems to occur at the Upgrade and initialize application, but I’m not sure how to debug it further or resolve it. Here’s my setup: Dockerfile: # Use the official Python runtime image FROM python:3.12.3 # Create the app directory RUN mkdir -p /opt/status-page/ # Set the working directory inside the container WORKDIR /opt/status-page/ # Set environment variables # Prevents Python from writing pyc files to disk ENV PYTHONDONTWRITEBYTECODE=1 # Prevents Python from buffering stdout and stderr ENV PYTHONUNBUFFERED=1 # Install system dependencies RUN apt-get update && apt install -y libpq-dev gcc # Create a system user and group RUN adduser --system --group status-page # Set ownership of the app directory RUN chown -R status-page:status-page /opt/status-page/ # Upgrade pip RUN pip install --upgrade pip # Copy the Django project to the container ADD status-page /opt/status-page/ # Grant execute permissions to upgrade.sh RUN chmod +x /opt/status-page/upgrade.sh # Install Python dependencies RUN python -m venv /opt/status-page/venv \ && /opt/status-page/venv/bin/pip install --no-cache-dir -r requirements.txt # … -
Decrypting image fields for Django REST API responses
I am trying to implement a system in which pictures are encrypted on my database, but when they are sent as a response to a user, this data becomes decrypted. Here is how I am encrypting... def encrypt_validated_data(obj, image_name): for data_key in obj.validated_data: if type(obj.validated_data[data_key]) is InMemoryUploadedFile: file_extension = obj.validated_data[data_key].image.format.lower() file_extension = "." + file_extension file_name = image_name + file_extension encrypted_file = obj.cipher.encrypt( obj.validated_data[data_key].read() ).decode("utf-8") obj.validated_data[data_key] = ContentFile( encrypted_file, name = file_name ) else: obj.validated_data[data_key] = obj.cipher.encrypt( obj.validated_data[data_key].encode("utf-8") ).decode("utf-8") return obj This code is called whenever an object is going to be saved to the database. It encrypts all the fields, and deals with the image case. Now, I need to decrypt this data for my response. My first thought was to manipulate the to_representation on the serializer such that I could decrypt each data part. This works great for text fields, but I haven't figured out a way to do it with image fields! This is the code so far... class ProfileSerializer(serializers.ModelSerializer): cipher = Fernet(settings.ENCRYPTED_FIELDS_KEY) profile_picture = serializers.ImageField(required=False) class Meta: model = YearRepresentative fields = [ "user_id", "name", "profile_picture", "pronouns" ] def to_representation(self, instance): encrypted_data = super().to_representation(instance) for key in encrypted_data: # We keep user ids encrypted if key … -
JavaScript `fetch()` won't post data in Django
The issue is encountered in the framework of Django. The related code lines are described below. These are the HTML lines, in which, the first div and the nested p will be filled with other HTML elements through a JavaScript function; the mentioned JavaScript function is not brought here for the sake of brevity: <form method="POST"> {% csrf_token %} <div id="bill"> </div> <div> <p id="total"></p> </div> <button onclick="record_order()">llllll</button> </form> Here is the JavaScript codes for the earlier record_order() used in button's onclick attribute in the HTML lines: function record_order() { fetch("http://localhost:8000/", { method: "POST", body: JSON.stringify({ "a": 1, "b": "vb" }), headers: { "Content-type": "application/json; charset=UTF-8", } }) .then((response) => response.json()) .then((json) => console.log(json)); } Also, there is the python class-based view whose post method is overridden like this: def post(self, request): print("---") print(request.POST) print("---") return HttpResponseRedirect("/") The button, when clicked, should call the JavaScript fetch() which will send the data to the server-side so it can be accessed via the request. But, the browser console logs out: order.js:42 POST http://localhost:8000/ 403 (Forbidden) record_order @ order.js:42 onclick @ (index):1331 and Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON On the other hand the terminal prints … -
Django form won't send post request
Hello I'm rebuilding my inventory application with the use of django forms and jinja template syntax I can't get the form to send a post request. here's my form in the template {% extends "inventory/base.html" %} {% block content%} <form action="inventory/stock/{{part_id}}" method="post">{% csrf_token %} {{form}}</form> <button type="submit" name="confirm" >Confirm</button> <button type="submit" name="cancel">Cancel</button> {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}> {{ message }}</li> {% endfor %} </ul> {% endif %} {% endblock %} here's my URL: path('stock/<int:part_id>/', views.add_stock_page, name='add_stock') here's my View: @login_required def add_stock_page(request, part_id): print('hi') template= loader.get_template('inventory/addStock.html') user= request.user form = StockForm() title = 'Add Stock' if 'confirm' in request.POST: print('confirm') messages.info(request,'confirm') if 'cancel' in request.POST: messages.info(request,'cancel') return render(request, 'inventory/addStock.html',{ 'user':user, 'form':form, 'title':title, 'part_id':part_id # 'messages':messages }) here's my form: class StockForm(forms.ModelForm): quantity = forms.IntegerField(required=True) price = forms.DecimalField(required=True) class Meta: model = Stock fields = [ 'supplier_id', 'brand_id', 'price' ] labels ={ 'quantity':'Quantity', 'supplier_id':'Supplier', 'brand_id':'Brand', 'price':'Price' }