Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Node npm error - could not determine executable to run
I was trying to install tailwind css using npm on my python django project in vscode, and for some reason kept running into the following error messages: npm ERR! could not determine executable to run So then i tried it with other project folders, same error. Other IDE's, same error. I then uninstalled and reinstalled node altogether, and yet that did not fix it. I now cant use tailwind in my project because of this as im unable to install it using npm, or even the django-tailwind packages. Any idea whats wrong with my Node? How do I fix it? -
Handle POST Request in DJANGO
I am new to DJANGO, and I am currently working on a project where I upload a file through a react page to a back-end handled by the DJANGO REST framework, after receiving the file I have to do some data processing. After some research I found that this logic is supposed to be in the views.py. So how do I create function which does this processing and how do I get it called whenever the server receives a new file or a POST request has been made. views.py from .models import FileStorage from rest_framework import viewsets from .serializers import FilesSerializer class FileViewSet(viewsets.ModelViewSet): queryset = FileStorage.objects.all() serializer_class = FilesSerializer -
Django - How to display image file in template
What I am trying to accomplish: I uploaded multiple images(3) and I am trying to display each images in different image tag. Here is my code; How are you doing it: I have attached my code to the question and explained the difficulties I have found in the code. codes below; Models.py class MultipleFile(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True) files = models.FileField(upload_to ='PostImages/%Y/%m/%d/', null=True, blank=True) is_image = models.BooleanField(default=False) is_video = models.BooleanField(default=False) Views.py def ForYouView(request): page_title = "For You" #All posters posts poster_profile = Post.objects.filter( Q(poster_profile=request.user)) #Post form if request.method == "POST": form = PostForm(request.POST) form_upload = MultipleFileForm(request.POST, request.FILES) if form.is_valid() and form_upload.is_valid(): post = form.save(commit=False) post.poster_profile = request.user post.save() form.save_m2m() my_files = request.FILES.getlist('files') for items in my_files: post_files = MultipleFile.objects.create(post=post, files=items) # Determine if it's an image or video based on mime type mime_type, _ = mimetypes.guess_type(post_files.files.name) if mime_type and mime_type.startswith('image/'): post_files.is_image = True elif mime_type and mime_type.startswith('video/'): post_files.is_video = True post_files.save() return redirect('site:foryou_view') else: form = PostForm() form_upload = MultipleFileForm() context = { 'page_title': page_title, 'poster_profile': poster_profile, 'form': form, 'form_upload': form_upload, } return render(request, 'foryou.html', context) Template.html {% if poster_profile %} {% for user in poster_profile %} {% if user.multiplefile_set.all|length == 3 %} {% for field in user.multiplefile_set.all … -
Can i connect my Youtube Channel Store to a Django E-commerce Website?
I am Django developer and I have a client who wants to connect his youtube store with the website that i'm gonna build with django. now i am confused that youtube will successfully connect the website or not. Anyone knows about this? Please let me know. -
How to select from the second field in the form - filtering data depending on the values of the first field?
Is it possible to somehow adapt something similar to my problem? I would like a list to appear in the form based on data from another list Select from the second field - filtering data - (contents) depending on the received values of the first field. For example. London Cafe London Restaurant London Fast Food Manchester Pizzeria Manchester Burgers I select a city in the form field and the second field is filtered by establishments. How to select from the second field in the form - filtering data depending on the values of the first field? class ExcludedDateForm(ModelForm): class Meta: model = models.ExcludedDate exclude = ('user', 'recurring',) def __init__(self, user=None, **kwargs): super(ExcludedDateForm, self).__init__(**kwargs) if user: self.fields['category'].queryset = models.Category.objects.filter(user=user) class FilterByUserMixin(LoginRequiredMixin): """ Filters the queryset with `self.request.user` in a specified `user_field` field. `user_field` defaults to "user". """ user_field = "user" def get_queryset(self, *args, **kwargs): return ( super() .get_queryset(*args, **kwargs) .filter(**{self.user_field: self.request.user}) ) class Book(models.Model): author = models.ForeignKey(MyUser, on_delete=models.RESTRICT) number_pages = models.PositiveIntegerField() title = models.CharField(max_length=1000) class BookUpdateView(FilterByUserMixin, UpdateView): model = Book template_name = "book/my_book_update_template.html" fields = ["number_pages", "title"] success_url = reverse_lazy("book-update-success") user_field = "author" . . .. .. ........ -
Best resourcefor learning django restframework?
I am learning drf on my own and i am having difficulties in understanding all the things by researching and i am also not sure that i am doing it correclty. So help me by suggesting best resources except official documentation. -
Why are my messages not showing in real-time using HTMX and WebSockets in Django?
I'm building a simple two-way chat system as a part of my web-app using HTMX WebSockets (htmx-ext-ws). The goal is to display incoming messages in real time without requiring a manual page refresh. The setup mostly works — messages are being saved to the database, and the WebSocket connection seems to establish correctly. However, new messages only appear after a page reload, and not in real time as expected. Here’s an overview of what I have: #chat.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Chat</title> <script src="https://unpkg.com/htmx.org@1.9.12"></script> <script src="https://unpkg.com/hyperscript.org@0.9.12"></script> <script src="https://unpkg.com/htmx-ext-ws@2.0.2"></script> <link rel="stylesheet" href="{% static 'css/chat.css' %}"> </head> <body> <div class="chat-container"> <div class="chat-header"> Chat Room </div> <div class="chat_messages" > {% for message in messages %} <div class="message-row {% if message.author.user == user %}my-message{% else %}other-message{% endif %}"> {% include "chat_rt/chat_message.html" %} </div> {% empty %} <div>No messages yet.</div> {% endfor %} </div> <form class="chat-input-area" id="chat-form" autocomplete="off" method="POST" hx-ext="ws" ws-connect="ws://127.0.0.1:8000/ws/chatroom/private-chat" ws-send _="on htmx:wsAfterSend set #chat-input.value to ''"> {% csrf_token %} {{ form.body }} <button type="submit">Send</button> </form> </div> <script src="{% static 'js/chat2.js' %}"></script> </body> </html> #chat_message.html {% if message.author.user == user %} <div class="message-content"> <div class="message-meta right"> <span class="time">{{ message.created|date:"H:i" }}</span> </div> <div class="body">{{ … -
Django/PostgreSQL: Unique constraint with a dynamic condition like expires_at > now()
I'm building a secure OTP system in Django. The model looks like this: class OTP(models.Model): MAX_ATTEMPTS = 3 DEFAULT_EXPIRE_IN_MINUTES = 1 class Purposes(models.IntegerChoices): LOGIN = 1, "Login" REGISTER = 2, "Register" VERIFY_PHONE = 3, "Verify Phone" VERIFY_EMAIL = 4, "Verify Email" otp_hash = models.CharField(max_length=64) purpose = models.IntegerField(choices=Purposes) phone = PhoneNumberField(null=True, blank=True) email = models.EmailField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) expires_at = models.DateTimeField() failed_attempts = models.PositiveSmallIntegerField(default=0) used = models.BooleanField(default=False) used_at = models.DateTimeField(null=True, blank=True) What I want to enforce: A user should not receive another OTP if there is already an unexpired (based on expires_at field), unused (used=False) OTP for the same purpose. The condition should apply either for: (phone, purpose) if phone is set, or (email, purpose) if email is set. And this logic must hold true even under concurrent requests. What I've tried so far: Application-level check with OTP.objects.filter(...) before creating a new one — this is not safe under race conditions. Adding a is_expired boolean field and a conditional UniqueConstraint like this: class Meta: constraints = [ models.UniqueConstraint( fields=["phone", "purpose"], condition=Q(is_expired=False), name="unique_active_phone_otp" ), models.UniqueConstraint( fields=["email", "purpose"], condition=Q(is_expired=False), name="unique_active_email_otp" ), ] But this requires updating the is_expired field manually or periodically when expires_at < now(), which adds operational complexity and is … -
{"status":"error","message":"An unexpected error occurred","errors":"[Errno 5] Input/output error"}
This problem occurs when I create an order in my project. I hosted it on GoDaddy, and the problem occurred only after hosting. If I run this locally, it will create the order. Understand this error Error saving data: dl {message: 'Request failed with status code 500', name: 'AxiosError', code: 'ERR_BAD_RESPONSE', config: {…}, request: XMLHttpRequest, …} this is the error it shows in the react front end {"status":"error","message":"An unexpected error occurred. "errors": "Input/output error"} and this is the error shows in the flutter app while creating the order -
How can I set up filtering in the form model of one field based on another when selecting?
I have 2 model tables. In the first table I have a form in the set in which there is one interesting field. This field can have the same values. If we consider the second table model - then in the second table model I placed 2 fields from the first table. And in these two fields - there is a field in which there can be duplicate values. I would like, if possible, to enter data into the second table - taking into account: selection of data from the city field and most importantly - so that after selecting in the city field - some filtering of the second field occurs. For example, filtering of two fields occurs according to the selected first field and is substituted into the second field. How can this be done. I select the city field - and so that the second field is filtered. How can I set up filtering in the form model of one field based on another when selecting? Help me please, I will be glad to any hint on how to do this? from django.db import models # Create your models here. TYPE_OBJECT = [ ("1", "Котельная"), ("2", "Сети"), … -
Production server Bad Request (Error: ValueError: Unknown endpoint type: 'fd')
This morning, my production website went down with a "Bad Request" error. It was working the day before, and I made no changes that might have caused the error. Below is the traceback I got in the asgi.log file. I can provide more information if needed, but not sure what. I have tried the following: Uninstalled all from requirements.txt, then reinstalled, and restarted the server Added '*' to ALLOWED_HOSTS, and set DEBUG=True, but this did not work, so I undid those changes. Rebooted the server The site works fine in my local machine, whether I use DEBUG = FALSE or DEBUG = True. Traceback (most recent call last): File "/home/raphaeluziel/raphi/venv/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/raphaeluziel/raphi/venv/lib/python3.12/site-packages/daphne/cli.py", line 171, in entrypoint cls().run(sys.argv[1:]) File "/home/raphaeluziel/raphi/venv/lib/python3.12/site-packages/daphne/cli.py", line 291, in run self.server.run() File "/home/raphaeluziel/raphi/venv/lib/python3.12/site-packages/daphne/server.py", line 130, in run ep = serverFromString(reactor, str(socket_description)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/raphaeluziel/raphi/venv/lib/python3.12/site-packages/twisted/internet/endpoints.py", line 1874, in serverFromString nameOrPlugin, args, kw = _parseServer(description, None) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/raphaeluziel/raphi/venv/lib/python3.12/site-packages/twisted/internet/endpoints.py", line 1794, in _parseServer plugin = _matchPluginToPrefix( ^^^^^^^^^^^^^^^^^^^^^ File "/home/raphaeluziel/raphi/venv/lib/python3.12/site-packages/twisted/internet/endpoints.py", line 1809, in _matchPluginToPrefix raise ValueError(f"Unknown endpoint type: '{endpointType}'") ValueError: Unknown endpoint type: 'fd' Traceback (most recent call last): File "/home/raphaeluziel/raphi/venv/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/raphaeluziel/raphi/venv/lib/python3.12/site-packages/daphne/cli.py", line 171, in entrypoint cls().run(sys.argv[1:]) … -
How can I configure the wrapping of a large long line of text in a form Django?
I have a form with OneToOneField where data is loaded from another table model. But I often have large data sizes there and the displayed text does not fit into the window size. Is it possible to somehow configure the text wrapping to 2-3 lines? How can I configure the wrapping of a large long line of text in a form? from django.db import models # Create your models here. class ArkiObject (models.Model): nameobject = models.TextField(verbose_name="Наименование объекта") def __str__(self): return self.nameobject TYPE_OBJECT = [ ("1", "Котельная"), ("2", "Сети"), ("3", "БМК"), ("4", "ЦТП"), ("5", "ТГУ"), ] TYPE_WORK = [ ("1", "Реконструкция"), ("2", "Капитальный ремонт"), ("3", "Строительство"), ] TYPE_CITY = [ ("1", "Бронницы"), ("2", "Луховицы"), ("3", "Павловский Посад"), ("4", "Раменское"), ("5", "Шатура"), ] class ArkiOneObject (models.Model): city = models.CharField( choices=TYPE_CITY, verbose_name="Выберите ОМСУ") typeobject = models.CharField( choices=TYPE_OBJECT, verbose_name="Выберите тип объекта") typework = models.CharField( choices=TYPE_WORK, verbose_name="Выберите тип работ") nameobject = models.OneToOneField(ArkiObject, verbose_name="Наименование объекта", on_delete=models.CASCADE) from django import forms from .models import * class FormOne (forms.ModelForm): class Meta: model = ArkiOneObject fields = "__all__" class FormTwo (forms.ModelForm): class Meta: model = ArkiTwoObject fields = "__all__" class FormThree (forms.ModelForm): class Meta: model = ArkiObject fields = "__all__" <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <title>title</title> </head> … -
Setup to deploy different django app do different environment(Prod/UAT)
I'm building an application using Django for backend and React for frontend and there's need to deploy do different environments, UAT and PROD. How do I set up the Nginx and Django environments? Please share your views or resources that could be helpful. Recommendations on tools for building an industry pipeline is also welcome. Note: I'm still using raw IP -
Django URL matching but displaying 'Page Not Found'
I'm getting a page not found error for a url I know is defined in urls.py - exact same code works on the qa server, but for some reason on the live server it gives a 404 error. 404 error returned even though it says the url is matched! I put debug=True temporarily on the live server to get the list of urls. Going a little crazy here, any ideas? -
Django project -createsuperuser Doesnt work
I am facing an issue while creating my superuser using the following command: ./manage.py createsuperuser, it seems that there is no error but the line where í can set my email and password doesnt appear enter image description here Could someone kindly help me understand the root cause of this problem? If you need additional screenshots, please feel free to ask. Thank you for your assistance. Best regards, -
Password doesnt get saved from the signup request in django-allauth
I have a django app and i am using django-allauth to authenticate users.I dont have anything complex setup right now, all i am trying to do is let the user signup through email and password and verify their email before they can login. I am testing the apis through postman right now and when i hit the singup endpoint, everything works fine: the user object is saved in database with the relevant fields(email, phone number, role) but the password does not get saved and because of this i am not able to login or do anything else in the authentication process. This is my setup: I am using the headless apis rather than regular ones. This is my settings.py INSTALLED_APPS = [ .... 'allauth', 'allauth.account', 'allauth.headless', 'allauth.usersessions', ] AUTHENTICATION_BACKENDS = [ # `allauth` specific authentication methods, such as login by email 'allauth.account.auth_backends.AuthenticationBackend', # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend' ] #ALLAUTH SETTINGS ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_EMAIL_VERIFICATION_BY_CODE_ENABLED = True ACCOUNT_SIGNUP_FIELDS = [ 'email*', 'phone*', 'password*', ] ACCOUNT_SIGNUP_FORM_CLASS = "user_onboarding.forms.CustomSignupForm" ACCOUNT_ADAPTER = 'user_onboarding.adapter.CustomAccountAdapter' ACCOUNT_LOGIN_METHODS = {"email"} HEADLESS_ONLY = True HEADLESS_FRONTEND_URLS = { "account_confirm_email": "/account/verify-email/{key}", "account_reset_password": "/account/password/reset", "account_reset_password_from_key": "/account/password/reset/key/{key}", "account_signup": "/account/signup", "socialaccount_login_error": "/account/provider/callback", } ACCOUNT_PHONE_VERIFICATION_ENABLED = False … -
Django Multi-Database ValueError: "Cannot assign Role object: the current database router prevents this relation"
I'm encountering a ValueError in my Django application when trying to save a User object with a related UserRoleAssociation in the admin interface. The error occurs in a multi-database setup where both the UserRoleAssociation and Role models are intended to use the members database. The error message is: ValueError: Cannot assign "<Role: Role object (67c43a2e-c4e7-4846-bd31-700bf5d35e82)>": the current database router prevents this relation. I have a Django project with two databases: default and members. The User, UserRoleAssociation, and Role models are all configured to use the members database via admin classes. The error occurs when saving a User object with an inline UserRoleAssociation in the Django admin. Models # models.py class Role(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) role_name = models.CharField(max_length=255, unique=True) class Meta: db_table = "roles" class UserRoleAssociation(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE) role = models.ForeignKey("Role", on_delete=models.CASCADE) def __str__(self): return f"{self.role.role_name}" class Meta: unique_together = ["user", "role"] db_table = "user_role_association" class User(models.Model): phone_number = models.CharField(max_length=15) is_premium = models.BooleanField(default=False) roles = models.ManyToManyField("Role", through=UserRoleAssociation, related_name="users") class Meta: db_table = "users" app_label = "members" base_manager_name = 'objects' default_manager_name = 'objects' Admin Configuration I use a custom MultiDBModelAdmin and MultiDBTabularInline to enforce the members database: # admin.py class MultiDBModelAdmin(admin.ModelAdmin): using = "members" def save_model(self, request, obj, … -
How to access a Django site from another device on a local network
I'm running a Django site on my computer and I want to access it from another device on the same Wi-Fi network (for example, from a phone or another laptop). I tried running python manage.py runserver, but I can only access the site from the same computer using localhost. I don’t know how to make the site accessible from other devices. How can I properly configure Django and my computer so that the site is accessible from other devices? To be honest, when trying to find a solution, I found a couple of options where I needed to merge the project into different services, but that doesn't work for me. Thanks in advance! -
Создание профиля пользователя в Django при регистрации: где лучше размещать логику — во вьюхе или в форме? Плюсы, минусы и рекомендации для начинающих [closed]
asdasdadsdadadsadsorry for that question, guys пытаюсь скопировать стек оверфлоуasdasdadsdadadsadsorry for that question, guys пытаюсь скопировать стек оверфлоуasdasdadsdadadsadsorry for that question, guys пытаюсь скопировать стек оверфлоу -
Unable to find GDAL library in conda env
I have a django project configured with pycharm. I am using a conda env for packages installations. I have installed gdal. But when I run server, I see: django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal310", "gdal309", "gdal308", "gdal307", "gdal306", "gdal305", "gdal304", "gdal303", "gdal302", "gdal301"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. I have added this at top of settings.py: import os os.environ['GDAL_LIBRARY_PATH'] = r'C:\Users\Admin.conda\envs\my-env\Library\bin\gdal.dll' I even added GDAL_LIBRARY_PATH globally as user variable, but I still see this error. How to get it working? -
Why is my selenium script blocked in production in headless mode, while it works completely fine in local enviroment? i use python
i have a selenium web scrapper, that runs well in my local development environment even in headless mode. However when i deploy it in production in a Linode Ubuntu VPS, somehow it fails with a Timeout exceeded message.Any help would be highly appreciated. I use django management commands to run the script, and it fetches data from a japanese car website. Here is the code import json from numbers import Number from pathlib import Path import traceback import asyncio import warnings import time import pandas as pd from inspect import Traceback import re from bs4 import BeautifulSoup from django.views.i18n import set_language from google_currency import convert from deep_translator import GoogleTranslator,LingueeTranslator import undetected_chromedriver as UC from selenium import webdriver from selenium.webdriver import DesiredCapabilities from selenium.webdriver.chrome.service import Service from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.select import Select from selenium_stealth import stealth from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import NoSuchElementException, TimeoutException, NoAlertPresentException from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import service from base_selenium_browser import BaseSeleniumBrowser from basebrowser import BaseBrowser from bs4 import BeautifulSoup import random from random import randint from bs4 import SoupStrainer from cleaning.cleaning_data import DataProcessor from saving_data.saving_data import SavingData from webdriver_manager.chrome import ChromeDriverManager BASE_PATH = Path(__file__).resolve().parent.parent class PriceFinderBot(BaseSeleniumBrowser): def __init__(self): self.__data_saver = … -
Shouldn't the call to django_stubs_ext.monkeypatch should be inside a TYPE_CHECKING check?
Simple question here about django_stubs_ext. Shouldn't the monkey patching occur only during TYPE_CHECKING ? Something like this: # settings.py if TYPE_CHECKING: import django_stubs_ext django_stubs_ext.monkeypatch() -
pythonanywhere getting an error when deploying
Something went wrong :-( Something went wrong while trying to load this site; please try again later. Debugging tips If this is your site, and you just reloaded it, then the problem might simply be that it hasn't loaded up yet. Try refreshing this page and see if this message disappears. If you keep getting this message, you should check your site's server and error logs for any messages. Error code: 502-backend your text I WAS TRYING TO DEPLOY A DJANGO PROJECT VIA PYTHONANYWHERE BUT I GET THIS ERROR Something went wrong :-( Something went wrong while trying to load this site; please try again later. Debugging tips If this is your site, and you just reloaded it, then the problem might simply be that it hasn't loaded up yet. Try refreshing this page and see if this message disappears. If you keep getting this message, you should check your site's server and error logs for any messages. Error code: 502-backend -
How do I structure a Django REST Framework API backend when the frontend is already built?
I'm building a Visitor Management System (VMS), and I've been given a complete frontend to work with. My task is to build the API-based backend using Django and Django REST Framework, which I'm familiar with from smaller projects. However, I'm struggling to organize the backend efficiently and expose the right endpoints that match what the frontend expects. Set up Django and Django REST Framework. Defined my models (e.g., VisitorPreRegistration, User). Started creating serializers and basic viewsets. My Questions: What is the best way to structure a Django API-only project, especially when the frontend is decoupled? Are there packages or patterns (like cookiecutter-django, DRF extensions, or project templates) that help speed up development and reduce boilerplate? How do I effectively map frontend forms and filters (e.g., visitor type, host search, arrival time) to backend endpoints? 🔍 What I tried: I’ve read the Django and DRF documentation, and tried watching a few YouTube tutorials, but most assume a monolithic approach or skip the API-only setup with an existing frontend. -
django-minify-html breaks Google Analytics injection
I'm running into an issue and would appreciate some pointers. I have a production Django app where I included Google Analytics using a context processor and conditionally render it in my base.html template like this: <!-- Google Analytics --> {% if GOOGLE_ANALYTICS_ID %} <script async src="https://www.googletagmanager.com/gtag/js?id={{ GOOGLE_ANALYTICS_ID }}"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', '{{ GOOGLE_ANALYTICS_ID }}'); </script> {% endif %} <!-- End Google Analytics --> Everything was working fine but the GA tracking completely breaks after enabling django_minify_html These are my current settings: For base.py: USE_MINIFICATION = DJANGO_ENV == "production" MINIFY_HTML = { "enabled": USE_MINIFICATION, "remove_comments": True, "minify_js": False, "minify_css": True, } For production.py from .base import MIDDLEWARE as BASE_MIDDLEWARE MIDDLEWARE = list(BASE_MIDDLEWARE) # Insert MinifyHtmlMiddleware after WhiteNoiseMiddleware try: whitenoise_index = MIDDLEWARE.index("whitenoise.middleware.WhiteNoiseMiddleware") MIDDLEWARE.insert(whitenoise_index + 1, "django_minify_html.middleware.MinifyHtmlMiddleware") except ValueError: try: security_index = MIDDLEWARE.index("django.middleware.security.SecurityMiddleware") MIDDLEWARE.insert(security_index + 1, "django_minify_html.middleware.MinifyHtmlMiddleware") except ValueError: MIDDLEWARE.insert(0, "django_minify_html.middleware.MinifyHtmlMiddleware") Has anyone encountered this before? I've minify_js to False in hopes to exclude the GA script but keep on getting the console error. Would love to hear any tips or workarounds for the best way to exclude GA tracking code from compression/minification. Thanks!