Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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' } -
set priority on Queryset in django
this is my product and category model: class Category(models.Model): name = models.CharField(max_length=100) class Product(models.Model): ... category = models.ForeignKey(Category, related_name="products", on_delete=models.CASCADE) I want a list of all products with priority order. e.g. categories_ids = [3,5,1,4,2] now I want data to order like this [product_with_category_3, product_with_category_3, product_with_category_3, product_with_category_5, product_with_category_1, product_with_category_1, ...] -
Django Admin Theme Switching Between Grappelli and Jazzmin Not Working (Session-Based)
Problem Statement: I am working on a Django e-commerce project and want users to switch between two admin themes: Grappelli and Jazzmin using Django sessions. I have implemented a session-based theme switcher, but: The admin panel always loads Grappelli by default. The switch button appears, but clicking it does not apply the correct theme. After switching to Jazzmin, I get a "Page Not Found" error (404). Project Setup 1. Installed Apps (settings.py) INSTALLED_APPS = [ "grappelli", # Defaulting to Grappelli "jazzmin", # Want to switch between these two "colorfield", "core.apps.CoreConfig", # My core app "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.humanize", ] Grappelli is loading by default, even when the session should switch to Jazzmin. 2. Middleware for Dynamic Theme Switching (core/middleware.py) from django.utils.deprecation import MiddlewareMixin class DynamicAdminThemeMiddleware(MiddlewareMixin): def process_request(self, request): from django.conf import settings if request.session.get("admin_theme") == "grappelli": settings.INSTALLED_APPS = ["grappelli"] + [app for app in settings.INSTALLED_APPS if app != "jazzmin"] else: settings.INSTALLED_APPS = ["jazzmin"] + [app for app in settings.INSTALLED_APPS if app != "grappelli"] I suspect modifying settings.INSTALLED_APPS dynamically might not be effective. Does Django require a restart for INSTALLED_APPS changes to take effect? Middleware is included in settings.py: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "core.middleware.DynamicAdminThemeMiddleware", # Custom middleware … -
Django: Best way to create logs when updating a model in bulk
I am developing a Django system where I have a main model and a log/history model to record changes. My main model: class Modelo(models.Model): user_a = models.ForeignKey(User, on_delete=models.CASCADE, related_name="delegated_signatures") user_b = models.ForeignKey(User, on_delete=models.CASCADE, related_name="received_delegations") is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) And the history model: class ModeloLogHistory(models.Model): modelo = models.ForeignKey(Modelo, on_delete=models.CASCADE) changed_by = models.ForeignKey(User, on_delete=models.DO_NOTHING) change_type = models.CharField(max_length=50, choices=ChangeType.CHOICES) previous_data = models.JSONField(null=True, blank=True) new_data = models.JSONField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) The logic works well for individual changes, but there is a scenario where an administrator can deactivate all records at once (is_active = False). This could generate a large volume of logs in the database, making me wonder about the best approach to handle these changes efficiently. -
password rest email notification or just email notification
I have a project in DJANGO and in the settings GEMENI is persitant on hard codeing my email and i dont want it hard coded for a password reset i want it to read from the .db file and be able to use multy emails not just gmail attached will be the settings.py file and gemini is consitant on keeping the setting file like this and im at a lose on this any help would be great it is a great project that users can apply for almost anything the model based is project tracker enter image description here -
How to migrate Django from local sqlite3 to postgresql Docker container?
I'm trying to learn Django with some demo projects and want to migrate from sqlite3 to a local postgresql container for dev work. When I try to run uv run python manage.py migrate, I get the following exception: django.db.utils.OperationalError: connection failed: connection to server at "127.0.0.1", port 5432 failed: FATAL: password authentication failed for user "myuser" While the container is running, the database is accessible via psql, and my pg_hba.conf looks like it should be allowing authentication: # TYPE DATABASE USER ADDRESS METHOD # "local" is for Unix domain socket connections only local all all trust # IPv4 local connections: host all all 127.0.0.1/32 trust # IPv6 local connections: host all all ::1/128 trust # Allow replication connections from localhost, by a user with the # replication privilege. local replication all trust host replication all 127.0.0.1/32 trust host replication all ::1/128 trust host all all all scram-sha-256 I'm creating and running my postgresql container with: docker run --name=db_container -d -e POSTGRES_DB=mydatabase -e POSTGRES_USER=myuser -e POSTGRES_PASSWORD=mypassword -p 5432:5432 postgres:16.2 My .env file contains: POSTGRES_DB=mydatabase POSTGRES_USER=myuser POSTGRES_PASSWORD=mypassword HOST=localhost PORT=5432 My settings.py file contains: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': config('POSTGRES_DB'), 'USER': config('POSTGRES_USER'), 'PASSWORD': config('POSTGRES_PASSWORD'), 'HOST': config('HOST'), 'PORT': config('PORT'), } } … -
What is the correct way of using Django's get_context_data() method to add key-value pairs to a context?
How can Django's get_context_data() method be used to add new key-value pairs to a context in the views.py file? I am following along with a tutorial and thus far everything has worked well, however at the moment I can't get the added context entries to populate the html template. Here's what I've got thus far, based on the instructions in the tutorial: views.py: from django.shortcuts import render from django.views.generic import TemplateView # Create your views here. class AboutPageView(TemplateView): template_name = "about.html" def get_context_data(self, **kwargs): # new context = super().get_context_data(**kwargs) context["contact_address"] = "123 Jones Street" context["phone_number"] = "01234 678910" return context about.html (the template): <h1>Company About Page</h1> <p>The company address is {{contact_address}}.</p> <p>The company phone number is {{phone_number}}.</p> urls.py: from django.urls import path from .views import home_page_view, AboutPageView urlpatterns = [ path("about/", AboutPageView.as_view()), path("", home_page_view) ] This results in an output which doesn't drag through the values associated contact_address and phone_number to the website when I run the dev server: What I am doing wrong? I've double-checked the sample code several times, and can't see that I'm mis-typing anything. I've also browsed for solutions online but many of the responses seem to relate to scenarios that are a bit far ahead … -
Problems in React axios request to Django backend ( rest framework ) , Error 404 Not Found
I have created a backend with Django so that a user can subscribe to services provided by other users. If I add the user to another user's service list from Thunder, the request succeeds and the user is added, but if I try to do it from my react app it returns the error. AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} code : "ERR_BAD_REQUEST" config : {transitional: {…}, adapter: Array(3), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message : "Request failed with status code 400" name : "AxiosError" request : XMLHttpRequest onabort : ƒ handleAbort() onerror : ƒ handleError() onload : null onloadend : ƒ onloadend() onloadstart : null onprogress : null onreadystatechange : null ontimeout : ƒ handleTimeout() readyState : 4 response : "{"affiliations":["Expected a list of items but got type \"int\"."]}" responseText : "{"affiliations":["Expected a list of items but got type \"int\"."]}" responseType : "" responseURL : "http://127.0.0.1:8000/api/listofmembers/create/" responseXML : null status : 400 statusText : "Bad Request" timeout : 0 upload : XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, …} withCredentials : false [[Prototype]] : XMLHttpRequest response : {data: {…}, status: 400, statusText: … -
django - saving image to Supabase bucket, but image is blank
I'm uploading image through Angular - django - Supabase s3. To send image to Supabase bucket im using django-storages module. When i get image from supabase image gets corrupted with additional bytes. Here is my settings of django-storages STORAGES = { "staticfiles": { "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage", }, "default": { "BACKEND": "storages.backends.s3.S3Storage", "OPTIONS": { "bucket_name": os.getenv('SUPABASE_STORAGE_BUCKET_NAME'), "region_name": os.getenv('SUPABASE_S3_REGION_NAME'), "access_key": os.getenv('SUPABASE_S3_ACCESS_KEY_ID'), "secret_key": os.getenv('SUPABASE_S3_SECRET_ACCESS_KEY'), "endpoint_url": os.getenv('SUPABASE_S3_ENDPOINT_URL') }, } } Here is my django code of image upload method of Viewset. @action(detail=True, methods=['post'], url_path='image', parser_classes=[FormParser, MultiPartParser]) def image_upload(self, request, pk=None): project = self.get_object() image = request.FILES['image'] project.image = image project.save() projectReadSerializer = ProjectReadSerializer(project) return Response(data = projectReadSerializer.data) whenever I post the image, I get blank image from the supabase bucket, which has more bytes than the original. Any solutions? I've tried to download the image, here is the result: original and bucket image I've also checked the image using PIL and it seemed fine: def image_upload(self, request, pk=None): project = self.get_object() image = request.FILES['image'] img = Image.open(image) img.show() project.image = image project.save() projectReadSerializer = ProjectReadSerializer(project) return Response(data = projectReadSerializer.data) so the problem is in project.image = image part of code, as it seems. -
ImportError for venv/lib64/python3.9/site-packages/oracledb/base_impl.cpython-39-x86_64-linux-gnu.so
I have a Django app that runs fine under runsslserver, but when I run it under Apache, the traffic gets to the app, but 'import oracledb' fails. I was using cx_Oracle previously (which also threw an ImportError) and switiched to oracledb hoping that would solve the problem. I tried compiling the mod_wsgi.so (5.0.2), but again I get the same error. Any suggestions? This is on RHEL 9, python 3.9 -
Why some staticfiles of Django wont add
I try to load all files from static folder that is located in root of my project. Some of them load successfuly, but some of them wont My folders: My_Project | -- static | -- folder that load successfuly \ -- javascripts folder that wont load I tried clearing web cache by pressing Ctrl+Shift+R and clearing it in browser settings, tried to restart my django server, tried to collect staticfiles Few of my settings that i've seen in other problems with static: BASE_DIR = Path(__file__).resolve().parent.parent INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'RecruitHelper', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ 'RecruitHelper/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', 'django.template.context_processors.static', ], }, }, ] STATIC_URL = '/static/' STATIC_ROOT = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ] -
Set wrong default value in Django model
So I added a new TimeField to my django model. When I did "python3 manage.py makemigrations" it asked me to choose two options, set a default value now or add one another way. I chose to set one now. I wasn't thinking and set it to "" which is incorrect format for a time field. I have tried everything, even manually in sqlite, removing the new field and more, but I still get an error when running "python3 manage.py migrate" which is saying this: django.core.exceptions.ValidationError: ['“” value has an invalid format. It must be in HH:MM[:ss[.uuuuuu]] format.'] If someone can help. me, it will be gladly appreciated! -
How can I prevent HistoricalModel Creation When Inheriting from Abstract Model?
I have an abstract base model, CompanyAwareModel, which includes historical tracking using TenantHistoricalRecords: class CompanyAwareModel(RequestChangeReasonModelMixin, TenantModel, TimeStampedModel, metaclass=CompanyAwareMeta): tenant_id = 'company_id' company = models.ForeignKey(Company, on_delete=models.CASCADE) history = TenantHistoricalRecords(inherit=True) class Meta: abstract = True To create a variant of this model without historical tracking, I defined another abstract model: class NoHistoryCompanyAwareModel(CompanyAwareModel): history = None class Meta: abstract = True Then, I define a concrete model inheriting from NoHistoryCompanyAwareModel: class Counter(NoHistoryCompanyAwareModel): ... However, when I run makemigrations, Django still creates a HistoricalCounter model, even though I explicitly set history = None in NoHistoryCompanyAwareModel. Interestingly, if I define NoHistoryCompanyAwareModel without inheriting from CompanyAwareModel, like this: class NoHistoryCompanyAwareModel(RequestChangeReasonModelMixin, TenantModel, TimeStampedModel, metaclass=CompanyAwareMeta): tenant_id = 'company_id' company = models.ForeignKey(Company, on_delete=models.CASCADE) history = None class Meta: abstract = True Then makemigrations does not create a historical table for Counter. Question Why does inheriting from CompanyAwareModel still create a historical table, even when history = None is explicitly set? And how can I ensure that Counter does not have a HistoricalCounter model while still inheriting from CompanyAwareModel? I expect that when I inherit the NoHistoryComapnyAwareModel from the CompanyAawreModel and set the history to None it won't create a historicalCounter for my model. -
Requiring 2FA (MFA) with Wagtail private pages. I think this works
This is one of those many times where I think I have a solution but I don't know if I'm doing something problematic I have a Wagtail site where I'm using 2FA sent by email and I have private articles that people have to log in to see Before the fix, when people logged in to the admin panel, everything worked as expected - they were required to enter a code that was emailed to them. But when people logged in to view a private article, they were able to log in without 2FA and once logged in, they could then browse to the admin panel without further challenges I think I fixed this by adding the following line to my url patterns: path("_util/login/", RedirectView.as_view(url="/accounts/login/?next=/accounts")), This works because when someone clicked on an article, they were redirected to _util/login, so the fix was re-redirecting that URL to allauth accounts just like admin/login is redirected This line follows the similar redirect for admin/login so my urls look like: urlpatterns = [ path("django-admin/", admin.site.urls), path("admin/login/", RedirectView.as_view(url="/accounts/login/?next=admin")), path("_util/login/", RedirectView.as_view(url="/accounts/login/?next=/accounts")), path("admin/", include(wagtailadmin_urls)), path("accounts/", include("allauth.urls")), path("documents/", include(wagtaildocs_urls)), path("search/", search_views.search, name="search"), ] But there are two things I'm asking about. First, I don't know how to …