Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is Python mostly used for in websites, and are there common issues?
I'm learning web development and I'm curious about how Python is used when it comes to websites. I know languages like HTML, CSS, and JavaScript are used on the front end, but where does Python come in? I’d like to understand: What part of a website Python is mostly used for Common Python frameworks for web development Any typical issues or challenges developers face when using Python for websites Any insights or examples would be appreciated! -
@login_required depending on setting?
While I expected this to be answered somewhere on StackOverflow, I haven't found it, so I apologise if this is a dupe. I want a setting to control whether certain views require a user to be logged in. If the setting is turned on, I want the views to behave as if they were decorated with @login_required, i.e. after the user logs in, they should be redirected back to the view. I don't mind putting code in the view to check the setting and calling redirect("account_login") if it's turned on. And, I suppose, passing request.get_full_path() as the next parameter would probably work. But redirecting to login and back seems a common enough use case for me to expect some elegant function in django.contrib.auth or django-allauth to do it, or that it would be easy to roll my own conditional @login_required decorator. Am I missing something? Thanks. -
Playwright's set_input_files() function doesn't work properly in python
I'm writing tests for my Django project using playwright and StaticLiveServerTestCase. In one test I need to choose two files using input[type=file] field and send them to the server. file_input = page.locator('input[type="file"]') file_input.set_input_files(["Input1.xlsx", "Input2.xlsx"]) But Playwright sending only first file and my test fails. I've tried to watch does input field has only one file, but it has both of them inside after choosing file_info = page.evaluate(""" element => { const files = Array.from(element.files); return files.map(file => ({ name: file.name, size: file.size, type: file.type })); } """, file_input.element_handle()) print("Files that JS sees:", file_info) That is the output: Files that JS sees: [{'name': 'Input1.xlsx', 'size': 5853, 'type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}, {'name': 'Input2.xlsx', 'size': 5851, 'type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'}] And Playwright outs only the first: input_value = file_input.input_value() print("Playwright's version:", input_value) Playwright's version: C:\fakepath\Input1.xlsx If you'll ask me I've tried absolute path for files and I've tried to change browsers. I've tried to test it manually and hadn't this problem. Django version 5.1.6 Playwright version 1.51.0 -
Django/Heroku error "Web process failed to bind to $PORT"
I am trying to configure a Django/PostgreSQL project to deploy on Heroku using Waitress. (I've only done this once successfully, several years ago using Guincorn). I am ultimately running into an error Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch The full error log is: 2025-04-09T07:09:48.289599+00:00 heroku[web.1]: State changed from crashed to starting 2025-04-09T07:09:52.235046+00:00 heroku[web.1]: Starting process with command `waitress-serve project.wsgi:application` 2025-04-09T07:09:52.781389+00:00 app[web.1]: Python buildpack: Detected 512 MB available memory and 8 CPU cores. 2025-04-09T07:09:52.781847+00:00 app[web.1]: Python buildpack: Defaulting WEB_CONCURRENCY to 2 based on the available memory. 2025-04-09T07:09:53.244456+00:00 app[web.1]: INFO:waitress:Serving on http://0.0.0.0:8080 2025-04-09T07:10:52.357945+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch 2025-04-09T07:10:52.370446+00:00 heroku[web.1]: Stopping process with SIGKILL 2025-04-09T07:10:52.421789+00:00 heroku[web.1]: Process exited with status 137 2025-04-09T07:10:52.445044+00:00 heroku[web.1]: State changed from starting to crashed" I initially thought this was a issue with defining PORT, but after leaving it out of my Procfile, it seems like Heroku is designating PORT locally, and so that problem may be resolved? I'm hoping someone might have some ideas that might cause "failed to bind to $PORT." Could it be an issue with DATABASE_URL? I am using Heroku's … -
What is best way to store small amount of data in BE (literally 1 line)?
I am currently working on functionality where users wants to keep a single message in header of a page to notify others of something happening in system. Essentially a header that can be updated by any user. As this header needs to be shown to every user in site I can't store it in local storage or user's table. Also this is a single line of message on a single page, so making a whole database table for this sounds utterly stupid. So to achieve this functionality for now I have added a json file in BE which just have this message in there and a view which allows users to edit this file. I have also placed this file in gitignore because data change in this should not reflect in git. This system works fine for now, but when I redeploy using Docker this file is removed and rebuilt losing the initial message. Is there a better way to store and update this data? Or any way to not lose my data on redeploy? userdata.json { message: "Holiday tomorrow, please report any issues by 3." } Reading data in Django View try: if not os.path.exists(USERDATA_FILE): # Create the file … -
Can't establish connection between web socket and server
I'm writing a chat app using django channels, redis and daphne. When I try to submit the message and tap on the button I have GET query, but I've written js in my html file and it has to prevent standart behaviour of this form. I don't know why doesn't it establish the connection and just send GET query, what's wrong here? I've checked redis server, It works. I've installed all required modules, I've checked It with gpt, nothing helps. How to make it establish the connection? consumer.py: import json from channels.generic.websocket import AsyncWebsocketConsumer from channels.db import database_sync_to_async from django.apps import apps class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.chat_name = self.scope['url_route']['kwargs']['chat_name'] await self.channel_layer.group_add(self.chat_name, self.channel_name) await self.accept() @database_sync_to_async def save_message(self, text_data): Chat = apps.get_model('chat', 'Chat') ChatMessage = apps.get_model('chat', 'ChatMessage') User = apps.get_model('auth', 'User') chat = Chat.objects.get(chat_name=text_data['chat_name']) sender = User.objects.get(username=text_data['sender']) ChatMessage.objects.create( chat=chat, body=text_data['message'], sender = sender, ) async def receive(self, text_data): print('Received from frontend:', text_data) data_json = json.loads(text_data) await self.save_message(data_json) event = {"type": "send_chat_message", "message": data_json} await self.channel_layer.group_send(self.chat_name, event) async def send_chat_message(self, event): await self.send(text_data=json.dumps({"message": event["message"]})) chat.html: {% extends "base.html" %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Chat</title> </head> <body> {% block content %} <div class="container"> <h2>Chat with … -
Quiero usar el usuario que esta logueado en mi modelo de wagtail
Hola a todos primero que nada muchas gracias de antemano tengo este problema: Estoy haciendo una página de blog con wagtail y me gustaria que le autor fuera el usuario que esta logueado pero e intentado de mil maneras y nada me funciona siempre el usuario es None class BlogPage(Page): autor = models.CharField(max_length=255) Como mencione antes quiero que ese campo sea el usuario logueado en el admin de wagtail. Mi idea era usar request pero al parecer no funciona con wagtail -
pytz library timezone conversion issue
I am trying to work with django and converting timezones between UTC and my timezone ("America/Winnipeg"), but I keep running into issues and I think there might be a bug. Here is my code: #UTC to "America/Winnipeg" utc1 = datetime.datetime(2025,4,8,12,00) utc1 = utc1.replace(tzinfo = pytz.utc) utc2wpg = utc1.astimezone(pytz.timezone("America/Winnipeg")) wpgb2utc = utc2wpg.astimezone(pytz.utc) print(f"UTC Time: {utc1}") print(f"UTC to Winnipeg Time: {utc2wpg}") print(f"Winnipeg back to UTC Time: {wpgb2utc}") #America/Winnipeg to UTC wpg1 = datetime.datetime(2025,4,8,7,0) wpg1 = wpg1.replace(tzinfo = pytz.timezone("America/Winnipeg")) wpg2utc = wpg1.astimezone(pytz.utc) utcb2wpg = wpg2utc.astimezone(pytz.timezone("America/Winnipeg")) print(f"Winnipeg Time: {wpg1}") print(f"Winnipeg to UTC Time: {wpg2utc}") print(f"UTC back to Winnipeg Time: {utcb2wpg}") When you run the UTC to "America/Winnipeg" block, you get the output: UTC Time: 2025-04-08 12:00:00+00:00 UTC to Winnipeg Time: 2025-04-08 07:00:00-05:00 Winnipeg back to UTC Time: 2025-04-08 12:00:00+00:00 But when you run the exact same timezone converting back from Winnipeg to UTC, you get this output: Winnipeg Time: 2025-04-08 07:00:00-06:29 Winnipeg to UTC Time: 2025-04-08 13:29:00+00:00 UTC back to Winnipeg Time: 2025-04-08 08:29:00-05:00 There is clearly a discrepancy in the timezone conversions. Is there an issue with my code or is there an issue with the pytz library's conversion. Are you having the same output? Btw I am using Python 3.13 -
unresponsive boostrap on google chrome from my django app
Here is my app directory Here is the head of my html `{% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title> Asoro Auto </title> <link href=" {% static 'Dashboard/css/bootstrap.min.css'% }" rel="Stylesheet" > </head>` Here is the body that contains tags styled according to bootstrap convention `<div class="container"> <div class="row"> <div class="col">AB2C1D1 </div> <div class="col">AB2C1D2 </div> <div class="col">AB2C1D3 </div> <div class="col">AB2C1D4 </div> </div> <div class="row">AB2C2 </div> <div class="row">AB2C3 </div> <div class="row">AB2C4 </div> </div>` Here is the bootstrap script added before the end of my html body tag `<script src=" {% static 'Dashboard/js/bootstrap.min.js'% }"></script> </body>` In my settings.py here are my some necessary configurations highlighted for the local twitter bootstrap to work `STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR/"static",` ] -
Django with a single db raises "the current database router prevents this relation" when intializing model
In django I have the following database models: ParentA ParentB Connector which has a foreign key that references the model ParentA and a foreign key that references the model ParentB The Connector model: from django.db import models class Connector(models.Model): class Meta: ordering = ["parent_a"] unique_together = (("parent_a", "parent_b"),) parent_a = models.ForeignKey( ParentA, on_delete=models.CASCADE, related_name="connected_bs", ) parent_b = models.ForeignKey( ParentB, on_delete=models.CASCADE, related_name="connected_as", ) In my code each time a ParentA objects gets created I am finding which existing ParentB objects can get connected with it and I am creating Connector objects with the code that follows. The function that creates the Connector objects is a method of the ParentA, so self here is a ParentA object from django.db import models class ParentA(models.Model): ... def create_connectors(self): matching_p_b_objects = self.__get_matching_parent_b_objects() new_matching_p_b_objects = matching_p_b_objects.filter(~Q(connected_as__parent_a=self)) Connector.objects.bulk_create( [ Connector(parent_a=self, parent_b=parent_b) for parent_b in new_matching_p_b_objects ] ) The function is called all the time and it mostly works but some times it randomly throws the error File "/code/backend/app/models/parent_a.py", line 989, in create_connectors [ File "/code/backend/app/models/parent_a.py", line 990, in <listcomp> Connector(parent_a=self, parent_b=parent_b) File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 541, in __init__ _setattr(self, field.name, rel_obj) File "/usr/local/lib/python3.10/site-packages/django/db/models/fields/related_descriptors.py", line 254, in __set__ raise ValueError( ValueError: Cannot assign "<ParentA: 340459>": the current database router … -
Django UpdateView Creates New Object Instead of Updating the Existing One
I'm having an issue with my Django update view. Although I see the correct data on the update form (i.e. the GET request pre-fills the form with the existing article’s content), when I submit the form the original article isn’t updated—instead, a new article is created with a new uid, and the original still remains with its original uid. I’ve verified that: My update view initializes the ModelForm with the existing instance using the instance parameter. My URL configuration includes the primary key (uid) in the URL. Below is a simplified version of my code. views.py: from django.shortcuts import render, get_object_or_404, redirect from .models import Article from .forms import ArticleForm def ArticleUpdate(request, pk): # Fetch the existing article using the uid passed via URL article = get_object_or_404(Article, uid=pk) if request.method == 'POST': # IMPORTANT: The form is instantiated with the existing instance! form = ArticleForm(request.POST, request.FILES, instance=article) if form.is_valid(): form.save() # Expect this to update, not create a new article return redirect('article-read', pk=article.uid) else: print("Form errors:", form.errors) else: form = ArticleForm(instance=article) context = {'form': form} return render(request, 'blog/article_form.html', context) urls.py: from django.urls import path from blog import views urlpatterns = [ path('articles/create/', views.ArticleCreate, name='article-create'), path('articles/<str:pk>/', views.ArticleRead, name='article-read'), path('articles/<str:pk>/update/', views.ArticleUpdate, name='article-update'), … -
Djoser Activation modification to set other field true instead of is_active
hey I am using the djoser for activation now I want the admin to activate the users from the edit user API in the email activation i want it to be like the email verification like but i want to set the email_verified to true in it instead of the is_active -
django application with firebase authentication
LLMs are failing me on this seemingly simple task, so I'm seeking community advise. I have a django application, which works fine. Both when I develop locally, and in production at https://my.domain Now, I need to add one more page to the application, that will be behind firebase authentication flow. The reason being I've already gotten a pool of users from my mobile application (unrelated to https://my.domain). I want to give access to the same users to their data they generated through my mobile app. My understanding was if they used same firebase ID (either google id, or apple id) as in app, it should be doable. Problems start pretty much off the bat. Here's what I did I've created firebase app and generated config data in firebaseConfig. Since I'm developing locally, I've added localhost to the list of Authorized domains list in firebase console. Google, Apple, Email logins are enabled. As they always were because of my mobile application. Service account credentials file is downloaded, stored, pointed at in django. I ran local server through python manage.py runserver I added login button in my login template. When I hit login (through google popup), list of my google accounts open. … -
Google OAuth2 Signup in Django: 'Bad Request' Error on First Signup Attempt
I'm working on integrating Google OAuth2 login/signup with Django, but I'm encountering an issue during the first signup attempt. The Flow: New User Registration using Google. The user clicks on the "Login with Google" button. The user is redirected to the Google OAuth2 consent screen and logs in. After successful Signup, Google redirects back to my app with a Bad Request - "POST /api/v1/auth/google/ HTTP/1.1" 400 Bad Request : this only happens first time the user tries to sign up, It returns a "Bad Request" error. The issue only occurs during the first signup, even though the user data is added to the database. If I try to login back with the same account using google now then i will be able to Login Successfully. Relevant Code : backend/api/urls.py : path('auth/google/', GoogleLogin.as_view(), name='google_login') backend/api/views.py : from django.conf import settings from django.http import HttpResponseRedirect from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from allauth.socialaccount.providers.oauth2.client import OAuth2Client from dj_rest_auth.registration.views import SocialLoginView class GoogleLogin(SocialLoginView): adapter_class = GoogleOAuth2Adapter client_class = OAuth2Client callback_uri = settings.REDIRECT_URI def get(self, request): return HttpResponseRedirect(redirect_to=settings.GOOGLE_AUTH_URL) backend/api/adapter.py: from allauth.socialaccount.adapter import DefaultSocialAccountAdapter from api.models import User class CustomSocialAdapter(DefaultSocialAccountAdapter): def pre_social_login(self, request, sociallogin): # Ignore existing social accounts, just do this stuff for new ones if sociallogin.is_existing: … -
Buttons On Click Functioning with same ID different and different attributes
I have an HTML webpage with a sample of buttons as shown part of a Django Application that fills in the name and town after inserting the values: {% for person in page_obj %} <button id="NotifyBtn" name="person.FName" town="person.LName">Press Me</button> {% endfor %} <button id="NotifyBtn" name="Billy" town="Bob">Press Me</button> <button id="NotifyBtn" name="Timmy" town="Tawin">Press Me</button> <button id="NotifyBtn" name="Milly" town="House">Press Me</button> Then I have a JS that does the following: document.getElementById("NotifyBtn").addEventListener("click", function(){ var name = this.getAttribute("name"); var town = this.getAttribute("town"); fetch("{% url 'alert_via_JSON_Response' %}", { method: "POST", headers: { "X-CSRFToken": "{{ csrf_token }}", "Content-Type": "application/json" }, body: JSON.stringify({ message: "Hi there: " + `${name} born in ${town}` }) }).then(response => response.json()) .then(data => alert(data.status)); }); In my Django application I have the following: def alert_via_JSON_Response(request): if request.method == 'POST': data = json.loads(request.body) message = data.get('message', "Error in sending email") return JsonResponse({"status": f"{message}"}) return JsonResponse({"status": f"No Message"}) Right now, when I click on the webpage, only one button works and sends a JSON response to the webpage, it doesn't work if I press another button after pressing the first button. Is there a way to press each button when needed and display the JSON response for each button? -
Dockerized Django app - `gunicorn: command not found` on AWS deployment
I have a Dockerized Django app that is deployed on AWS - after some recent updates to the Debian and PostgreSQL images that I'm using in the Dockerfile, the app is suddenly failing to start running successfully when it hits AWS due to an issue with gunicorn - pyenv: gunicorn: command not found This problem did not occur previously and, if I simply deploy a build based on the previous git commit (prior to making these updates), the app deploys and runs just fine. Furthermore, when I run the app locally via docker-compose up and bash into the container, I can run gunicorn commands no problem, so I'm not quite sure what the issue is - gunicorn is included in the requirements.txt file. Maybe I'll need to provide more info, but for starters, here is the current setup of the Dockerfile and requirements.txt files - I'll note the changes that have been made below them - Dockerfile FROM andrejreznik/python-gdal:py3.11.10-gdal3.6.2 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN apt-get update RUN apt-get upgrade -y RUN apt-get install postgresql-15 postgresql-server-dev-15 -y RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ ARG ALLOWED_HOSTS ARG AWS_ACCESS_KEY_ID … -
Django custom filter working in dev but not in prod
I created a custom template filter in django at myapp/templatetags/custom_filters.py. @register.filter(name='indian_number_format') def indian_number_format(value): """ Format the number in Indian style using the locale module (e.g., 1,00,00,000). """ if not isinstance(value, (int, float, Decimal)): print('Not a number', type(value)) return value try: # Set the locale to Indian (Hindi) locale.setlocale(locale.LC_NUMERIC, 'hi_IN') # Format the number using locale formatting formatted_value = locale.format_string("%d", value, grouping=True) return formatted_value except locale.Error: # Fallback in case the locale is not available on the system return value Using it in template like this {% extends "base.html" %} {% load custom_filters %} <p>{{number|indian_number_format}}</p> For example, if the number is 123456, the output should be 1,23,456 and this works fine in dev but the commas do not appear in prod which I have hosted on AWS. Any insight on what might be causing this issue would be helpful. Thanks. -
Deployed django app on apache 2 (403 Forbidden)
I am having trouble deploying my django app onto my linux server running apache2. I already have multiple appas running on this server without issue. I followed the same steps as i usually do, but for some reason, each time i go to the new app url, I am greeted with a 403 Forbidden error. Have checked the apache log and have received this Current thread 0x00007f11d99fcc40 (most recent call first): <no Python frame> [Mon Apr 07 13:34:27.128681 2025] [wsgi:warn] [pid 2703370:tid 139714642299968] (13)Permission denied: mod_wsgi (pid=2703370): Unable to stat Python home /home/tinytoes/surveyV2/venv. Python interpreter may not be able to be initialized>Python path configuration: PYTHONHOME = '/home/tinytoes/surveyV2/venv' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/tinytoes/surveyV2/venv' sys.base_exec_prefix = '/home/tinytoes/surveyV2/venv' sys.executable = '/usr/bin/python3' sys.prefix = '/home/tinytoes/surveyV2/venv' sys.exec_prefix = '/home/tinytoes/surveyV2/venv' sys.path = [ '/home/tinytoes/surveyV2/venv/lib/python38.zip', '/home/tinytoes/surveyV2/venv/lib/python3.8', '/home/tinytoes/surveyV2/venv/lib/python3.8/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Im not entirely sure if the error is relevent. Here are the permissions ive set for the app drwxr-xr-x 8 tinytoes www-data … -
django-x509 library - any way to use certificate authentication only on several pages of application and continue with password for others?
After searcxhing and investigating various X509 libs for django I found this https://github.com/openwisp/django-x509 IMHO looks the best - even CA and certificate generation are present in admin UI. However, thinking now, how to use it the best way in my case - please, see short description and image below Data entry to the site should be done using two ways - automated POST from standalone application using cartificate authentication, and regular https for data watch and manual entry (sorry 4 typo in the image). It's important to remember, that application is standalone - no {% csrf_token %} in it indeed. So, general advice is needed. IMHO, the best way is to use cert autentication on the automated POST URL only, with password for other pages, but how? If mentioned above is not possible - needed to make two apps with sharing data model in common database to x509 app. Found 1 reply for sharing question with -1 rep here, not sure, that workable - advice is welcome. In addition. may happen user management problems in 2 apps etc, I think, that the first method is better. BTW, if the lib authors are here - sample of integraion into existing site … -
Django queryset annotate sum of related objects of related objects
I have class Book(models.Model): title = models.CharField(max_length=32) class Table(models.Model): book = models.ForeignKey(Book, related_name='tables') class TableEntry(models.Model): table = models.ForeignKey(Table, related_name='entries') value = models.FloatField() and want a queryset of books that has annotated the sum of all table entries in a book. I have tried Book.objects.all().annotate(sum=Sum('tables__entries')) but this does not seem to work. -
Making changes to database structure in django
Hi I am looking to get some guidance on how to properly make changes to the models in django. Currently I'm working on an app where I have previously defined models and have uploaded data for these models. However I would like to make some changes to the schema of the database and edit and add/delete some columns of the tables. I am running into some issues with this where django will not allow me to make migrations or migrate after certain changes. If anyone could give me some tips on why this is happening and best practices to follow when I am making changes like this it would be very helpful. Also currently I am using a sqlite3 db. I have tried to delete migrations and the database but had no success and I would also like a solution that is more practical if I wanted to make changes like this when the app in in production -
Error 'RecordSearchForm' object has no attribute 'is_game'
def index(request): game_data = GameDataEntry() update_progress = ProjectProgressEntry() work_hours = WorkHoursEntry() if request.method == "GET": form = RecordSearchForm(data=request.GET) if form.is_game is True: query = request.GET.get('entry_date') object_list = game_data.objects.filter(entry_date=query) return HttpResponse(object_list, content_type='text/plain') if form.is_work is True: query = request.GET.get('entry_date') object_list = work_hours.objects.filter(entry_date=query) return HttpResponse(object_list, content_type='text/plain') if form.is_Progress is True: query = request.GET.get('entry_date') object_list = update_progress.objects.filter(entry_date=query) return HttpResponse(object_list, content_type='text/plain') else: form = RecordSearchForm() return render(request, 'index.html', context={'form': form}) This is my Form class class RecordSearchForm(forms.Form): is_Progress = forms.BooleanField(widget=forms.CheckboxInput( attrs={'class': 'form-check-input', "id": "is_progress_update", "type": 'checkbox'})) is_game = forms.BooleanField(widget=forms.CheckboxInput( attrs={'class': 'form-check-input', "id": "is_game_update", "type": "checkbox"})) is_work = forms.BooleanField(widget=forms.CheckboxInput( attrs={'class': 'form-check-input', "id": "is_work_entry", "type": "checkbox"})) game_name = forms.ModelChoiceField(widget=forms.Select( attrs={'class': 'form-control', "id": "game_name"}), queryset=Games.objects.all()) entry_date = forms.DateField(widget=forms.DateInput( attrs={'class': 'form-control', "id": "date_entry", "type": "date"})) I am trying to make a search function to get the records based on the date of the entry for the models that are either game development, finished updates, or work hours but it's saying that is_game is not an attribute of my form but it's clearly there. can anyone tell me what I'm doing wrong or what I've missed -
Python gunicorn not working with Docker CMD
I have django App that also runs some Javascript templates with node. I'm struggling to run Gunicorn as the CMD of the Dockerfile. Here is my dockerfile: FROM node:22.12.0-alpine3.21 RUN mkdir /app COPY . /app WORKDIR /app/tools RUN npm install --loglevel verbose RUN npm run build WORKDIR /app RUN ls -la # Set environment variable for Python version ENV PYTHON_VERSION 3.10.10 # Install dependencies and Python 3.10 RUN apk update RUN apk update && apk add --no-cache \ build-base \ bash \ libffi-dev \ zlib-dev \ bzip2-dev \ ncurses-dev \ openssl-dev \ sqlite-dev \ readline-dev \ tk-dev \ gdbm-dev \ xz-dev \ libnsl-dev \ curl \ dcron RUN curl -O https://www.python.org/ftp/python/${PYTHON_VERSION}/Python-${PYTHON_VERSION}.tgz \ && tar -xvf Python-${PYTHON_VERSION}.tgz \ && cd Python-${PYTHON_VERSION} \ && ./configure --enable-optimizations \ && make -j$(nproc) \ && make altinstall \ && cd .. \ && rm -rf Python-${PYTHON_VERSION} Python-${PYTHON_VERSION}.tgz \ && python3.10 --version RUN ln -sf /usr/local/bin/python3.10 /usr/bin/python3 \ && ln -sf /usr/local/bin/pip3.10 /usr/bin/pip3 # Verify Python and pip installation RUN python3 --version && pip3 --version # Install pip and upgrade setuptools and wheel RUN pip3 install --no-cache --upgrade pip setuptools wheel RUN pip3 install -r requirements.txt EXPOSE 8000 ENV PYTHONPATH=/app WORKDIR /app CMD ["python3", "-m", "gunicorn", … -
can't retrieve images from filesystem with Next.js and Django
English is not my native language. I'm trying to deploy three Next.js apps and one Django API app(using Django ninja). the problem is I get "400 bad request" in my browser's console. https://MY_SERVER_DOMAIN/users/_next/image?url=https://MY_SERVER_DOMAIN/media/magazine/thumbnail/Methods-of-using-radish-in-diet.webp&w=1920&q=75 in local I can see the image but on production I get 400. my Nginx config: location /media/ { alias /home/USER/backend/media/; } location /api/v1 { include proxy_params; proxy_pass http://localhost:8000; } location /admin { include proxy_params; proxy_pass http://127.0.0.1:8000; } location / { include proxy_params; proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /doctors { include proxy_params; proxy_pass http://localhost:3001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } location /users { include proxy_params; proxy_pass http://localhost:3002; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } I saw many errors like this this in /var/log/nginx/error.log: 2025/04/06 13:44:21 [error] 41446#41446: *1 directory index of "/home/USER/users-front/.next/static/media//" is forbidden, client: 5.125.0.145, server: 176.97.218.11, request: "GET /users/_next/image/?url=%2Fusers%2F_next%2Fstatic%2Fmedia%2Fdoctor.07a8ef12.jpg&w=96&q=75 HTTP/1.1", host: "MY_SERVER_DOMAIN", referrer: "https://MY_SERVER_DOMAIN/users" but it should retrieve the image from Django media directory("backend/media") not Next.js! -
CORS headers not being added in django
Preface, I am aware of django-cors-headers not work I am getting the following error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ... (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 301. Here are the important parts of my settings.py. INSTALLED_APPS = [ ... corsheaders ... ] corsheaders is the last entry in INSTALLED_APPS MIDDLEWARE is: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "allauth.account.middleware.AccountMiddleware", ] So CorsMiddleware is at the top. And for CORS settings: CORS_ALLOW_CREDENTIALS = False CORS_ALLOW_ALL_ORIGINS = True And ALLOWED_HOSTS is: ALLOWED_HOSTS = ['*'] Online, this seems to be all that's needed to get CORS headers, but I am not getting them in the response. How do I fix this?