Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django's StatReloader returning error but server runs (although all requests written in red in the console)
I run python manage.py runserver in a folder (which worked finely yesterday) and get python : Watching for file changes with StatReloader Au caractère Ligne:1 : 1 + python manage.py runserver + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (Watching for fi...th StatReloader:String) [], RemoteException + FullyQualifiedErrorId : NativeCommandError but the server seems to work all the same even if requests are written in red in the console. I've tried what's advised here but nothing changes. I'm on Windows Powershell. -
why does this error in Template syntax keep coming for a django file?
I am new to python and I am working on a project. I completed the entire project but this error is not getting fixed. attaching the error and the code where there is error. this is the error TemplateSyntaxError at /meeting/ Invalid block tag on line 13: 'static'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/meeting/ Django Version: 5.2 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 13: 'static'. Did you forget to register or load this tag? Exception Location: D:\django-video-chat\venv\Lib\site-packages\django\template\base.py, line 577, in invalid_block_tag Raised during: chat.views.room Python Executable: D:\django-video-chat\venv\Scripts\python.exe Python Version: 3.12.8 code where there is error Can someone please help. -
International Phone Number Widget in Django Model Form
I am trying to include International code for the phone number, so users like easily select the country code from the drop down menu. I am following this example https://www.youtube.com/watch?v=Q5UPMEA5fX0 , but getting MultiWidget error. Here is how my ModelForm looks. Here is what the error looks like. It says I am missing 'widgets' argument. I am not able to find any examples online. Any help would be appreciated. -
Running Django tests ends with MigrationSchemaMissing exception
I'm writing because I have a big problem. Well, I have a project in Django where I am using django-tenants. Unfortunately, I can't run any tests as these end up with the following error when calling migrations: ‘django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (no schema has been selected to create in LINE 1: CREATE TABLE ‘django_migrations’ (‘id’ bigint NOT NULL PRIMA...’ The problem is quite acute. I am fed up with regression errors and would like to write tests for the code. I will appreciate any suggestion. If you have any suggestions for improvements to the project, I'd love to read about that too. Project details below. Best regards Dependencies [tool.poetry.dependencies] python = "^3.13" django = "5.1.8" # The newest version is not compatible with django-tenants yet django-tenants = "^3.7.0" dj-database-url = "^2.3.0" django-bootstrap5 = "^25.1" django-bootstrap-icons = "^0.9.0" uvicorn = "^0.34.0" uvicorn-worker = "^0.3.0" gunicorn = "^23.0.0" whitenoise = "^6.8.2" encrypt-decrypt-fields = "^1.3.6" django-bootstrap-modal-forms = "^3.0.5" django-model-utils = "^5.0.0" werkzeug = "^3.1.3" tzdata = "^2025.2" pytz = "^2025.2" psycopg = {extras = ["binary", "pool"], version = "^3.2.4"} django-colorfield = "^0.13.0" sentry-sdk = {extras = ["django"], version = "^2.25.1"} Settings.py import os from pathlib import Path from uuid import … -
Unable to open nginx with domain and can't open checkmk in Firefox browser
So I'm unable to open nginx with my domain name, arborhub.io and I can't open checkmk on the browser either. I decided to try & run checkmk behind nginx instead of apache, which I did successfully. I was hoping to fix the issue of the conflict between apache (checkmk) and nginx. But I still can't open either programs in my Firefox browser. I initially assumed my Django was causing this 502 gateway page error, but my Django server is running fine. Also my nginx is running with no problems either with `sudo sDoing 'status' on site arborhub: agent-receiver: running mkeventd: running rrdcached: running npcd: running nagios: running apache: running redis: running crontab: running Overall state: running ystemctl reload nginx` ● nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: en> Active: active (running) since Wed 2025-04-09 20:03:09 MDT; 3h 49min ago Invocation: 5e827ca7649a43b8bd078f49a64d7c77 Docs: man:nginx(8) Process: 10356 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_proc> Process: 10360 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (> Process: 15562 ExecReload=/usr/sbin/nginx -g daemon on; master_process on; > Main PID: 10361 (nginx) Tasks: 5 (limit: 18232) Memory: 4.4M (peak: 8.4M) CPU: 85ms CGroup: /system.slice/nginx.service ├─10361 "nginx: master process … -
Django unable to read "static" folder even though its available
It might look like a duplicate question but I read and tried various solutions and its not working for me. I'm using MAC OS and running venv with Django5. Getting error stating the "STATICFILES_DIRS setting does not exist.". The error output is as follows: Desktop/Projects/Django/moviestore/moviesstore/static' in the STATICFILES_DIRS setting does not exist. System check identified 1 issue (0 silenced). You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. April 10, 2025 - 02:45:10 Django version 5.0, using settings 'moviestore.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. settings.py import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = "**********" DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "home" ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "moviestore.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [os.path.join(BASE_DIR, 'moviesstore/templates')], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] WSGI_APPLICATION = "moviestore.wsgi.application" DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, { … -
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 …