Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Block Thread execution until completed in test Python Django
I have a Django app that needs to make some 3d service call to compute embedding. This call takes time and blocking execution and I want to make it async. For this I am using Thread. class MyView(): def create_answer_embedding(answer): embedding = long_computing_call(answer) db.write(embedding) <- pseudo code, the idea is that after creating the embedding, we create an AnswerEmbedding obj. in the db def post(request, *args, **kwargs): answer = request.data.get("answer") Thread(target=self.create_answer_embedding, args=(answer, )).start() return Response() So the thread starts calculating embedding and the view returns a response. Once calculating is finished, a new AnswerEmbedding object is created in the DB. Now I need to test it works properly. So if I just run a test that makes an api call: response = client.post("/my-view") answer_embedding = AnswerEmbedding.objects.get(answer__id=response.json()['id']) This test fails because it checks AnswerEmbedding.objects.get before it is actually created in the Thread. So, I need to somehow either make this Thread running sync or find a way to properly mock it. I could just mock the Thread but with this the test will not check if the embedding is created or not. Any ideas? Thanks -
How can I upload files asynchronously in Django? Can I use Celery for this purpose? I passed django form to the task and it didn't work
Normally, we can deploy celery for async. Can celery be used for asynchronous file uploading, which allows client to continue working on the website while big size of file being uploaded? I passed the forms to the task of the celery and I had an error like 'Object of type module is not JSON serializable'. Is there any way for async file uploading? -
Python Django {'user': [ErrorDetail(string='Incorrect type. Expected pk value, received BoundField.', code='incorrect_type')]}
I'm developing my backend on Django. I wrote a code for user registration under RegistrationView class, and it worked fine before. I had to incorporate email confirmation in it, which also worked fine on its own. However, after all of that was done, I added some conditions to ensure proper working, but I get the "string='Incorrect type. Expected pk value, received BoundField.'" and "Forbidden: /api/v1.0/user/register-patient/" error. Also, to clarify the workflow. Each user is assigned a JWT token while signing up. This token is different from the token sent to verify email. I named the latter "verification_token". So a user signs up, their 'is_active' field is set to False until they click on the link received in their email. Sendgrid email API was used to send the email. The email is only sent if the patient_serializer data is stored in the db. When the user clicks on the link received through email, their 'is_active' field is set to True, and they can now log in. Also, the actual sendgrid API key is a part of the code, I removed it here. My models.py file: from django.db import models from django.contrib.auth.models import User class VerificatonToken(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='token') … -
time data '' does not match format '%Y-%m-%d %H:%M:%S.%f'
Getting values from a database table and when the datefield is empty its giving me this error: time data '' does not match format '%Y-%m-%d %H:%M:%S.%f' first_date = users.work.values_list('work_date', flat=True) a = datetime.datetime.strptime(first_date, '%Y-%m-%d %H:%M:%S.%f') b = a.strftime("%m/%d/%Y") Basic output: 2022-06-02 11:16:41.012000+00:00 But it also will be null in table How I can skip this '' values, without try except and other huge lines of code? Thanks. -
How to test an HTMX Get request?
I'm working with Django and HTMX. One of my views receives a GET request and returns a whole page. However, if that GET request is from an HTMX element, the view will return a fragment: from django.shortcuts import render def view_example(request): if request.htmx: return render(request, 'fragment.html') else: return render(request, 'page.html') In page.html an HTMX element triggers a GET request that expects this fragment. It works - my functional tests see the result of the HTMX request. When I view it in the browser it also works. It doesn't work in my unit tests, though! I'm trying to test the two different types of responses: from django.test import TestCase class TestRequests(TestCase): def test_page(self): response = self.client.get('/') self.assertTemplateUsed(response, 'page.html') def test_fragment(self): headers = {'Hx-Request': 'true'} response = self.client.get('/', **headers) self.assertTemplateUsed(response, 'fragment.html') test_page passes, as expected, but test_fragment fails: AssertionError: False is not true : Template 'fragment.html' was not a template used to render the response. Actual template(s) used: page.html How do I simulate an HTMX request so that I can test my fragment logic? -
Unable to generate graph in django using xhtml2pdf
Can anyone share pdf example code with Graph in django, I am unable to create graph in pdf django -
Cannot get jwt tokens sent from frontend in backend
I'm a newbie at Django and simplejwt and I have encountered a problem. Tokens are being sent to me from our Angular frontend by the names of "app_token" and "access_token" but I cannot find a way to retrieve them in my Django code. I have tried names like "HTTP_APP_TOKEN" and "HTTP_ACCESS_TOKEN" and even had our frontend team rename the tokens but that didn't help as well. Does anyone have any ideas? -
Django+Nginx+uWSGI = 504 Gateway Time-out with pdf2image
I try to run Django application using Nginx+uWSGI. sudo apt update sudo apt install poppler-utils I installed poppler-utils. And my app tries to convert uploaded pdf pages to jpg with pdf2image module. During conversion, 504 Gateway Time-out is received after 1 minute. It works well when converting a small pdf (335KB) file to jpg. However, time-out is received when converting large capacity pdf (6.82MB). /etc/nginx/nginx.conf: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; } http { client_max_body_size 50M; upstream django { server unix:/home/ubuntu/myapp/uwsgi.sock; } proxy_send_timeout 300; proxy_read_timeout 300; proxy_connect_timeout 300; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } /etc/nginx/sites-enabled/default: server { listen 80 default server; listen [::]:80 default_server; root /var/www/html; server _name _; location / { include /etc/nginx/uwsgi_params; uwsgi_pass django; proxy_buffer_size 256k; proxy_buffers 16 256k; proxy_busy_buffers_size 512k; } ... } uwsgi.ini [uwsgi] chdir=/home/ubuntu/myapp module=myapp.wsgi:application master=True pidfile=/tmp/project-master.pid vacuum=True max-requests=5000 daemonize=/home/ubuntu/myapp/django.log home=/home/ubuntu/myapp/venv virtualenv=/home/ubuntu/myapp/venv socket=/home/ubuntu/myapp/uwsgi.sock chmod-socket=666 http-timeout=600 nginx error.log: 2022/06/02 17:11:20 [error] 1652#1652: *69 upstream timed out (110: Connection timed out) while reading response header from upstream, client: my_ip, server: _, request: "POST /upload/pdf/url HTTP/1.1", upstream: "uwsgi://unix:/home/ubuntu/myapp/uwsgi.sock", host: "my_server_ip", referrer: "http://my_server_ip/upload/pdf/url" I … -
Django on AWS elastic beanstalk: failed to generate rsyslog file with error Procfile could not be parsed
I am trying to add a custom Procfile to my Django elastic beanstalk environment but I am receiving the following error during the deploy: 022/06/02 08:14:22.827519 [INFO] Generating rsyslog config from Procfile 2022/06/02 08:14:22.827557 [ERROR] failed to generate rsyslog file with error Procfile could not be parsed 2022/06/02 08:14:22.827564 [ERROR] An error occurred during execution of command [app-deploy] - [GetToggleForceRotate]. Stop running the command. Error: failed to generate rsyslog file with error Procfile could not be parsed The Procfile I am using is the following: web: gunicorn --bind 127.0.0.1:8000 --workers=1 --threads=10 myapp.wsgi:application And the option I previously used in my .ebextentions configuration was option_settings: aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static aws:elasticbeanstalk:container:python: WSGIPath: myapp.wsgi:application NumProcesses: 1 NumThreads: 10 and it was running successfully. Any guess? Thank you -
how to make FILE type json serializable
I am trying to send json response in django but I am getting this error TypeError: Object of type File is not JSON serializable Error is coming because I am using type <class 'django.core.files.base.File'> in json response. So how can I convert this to json serializable formate? Code: user_id = User.objects.get(id=token_data['user_id']) all_posts = publicPost.objects.filter(user_id=user_id) post_ids = [] for post in all_posts: post_ids.append(post.id) images = {} for id in post_ids: img_obj = PostImage.objects.filter(post_id=id) imgs = [img_obj[0].image.file] try: x = img_obj[0].other_image1.file imgs.append(x) except ValueError: pass try: x = img_obj[0].other_image2.file imgs.append(x) except ValueError: pass try: x = img_obj[0].other_image2.file print('type', type(x)) imgs.append(x) except ValueError: pass images[id] = imgs return JsonResponse({'posts': post_ids, 'images': images}) -
How can I create a single user form page with django 1.11?
I'm trying to create a single user login page. How can I create that user? Can I just validate username and password in views ? Thank you for your help.. -
Django - classList.toggle is not working in django template [duplicate]
I am trying to animate a hamburger menu to transform into an 'x' when it is clicked. The javascript works in a normal html file, but when integrated with django for some reason it doesn't work. (Also I have checked that the javascript is linked properly to the django template.) const hamburger = document.querySelector(".hamburger"); hamburger.addEventListener("click", menu); function menu() { hamburger.classList.toggle("active"); } <link rel="stylesheet" href="{% static 'lng/css/navbar.css' %}" /> <link rel="stylesheet" href="{% static 'lng/css/main.css' %}" /> <script src="{% static 'lng/js/main.js' %} " type="text/javascript"></script> <button class="hamburger"> <span class="bar"></span> <span class="bar"></span> <span class="bar"></span> </button> .hamburger { display: inline; position: relative; z-index: 1; user-select: none; appearance: none; border: none; outline: none; cursor: pointer; transition: 0.1s; } .hamburger span { display: block; width: 33px; height: 4px; margin-bottom: 5px; position: relative; background-color: var(--dark); border-radius: 6px; z-index: 1; -webkit-transition: all 0.3s ease-in-out; transition: all 0.3s ease-in-out; } .hamburger:active .bar:nth-child(2){ opacity: 0; } .hamburger:active .bar:nth-child(1){ transform: translateY(8px) rotate(45deg); } .hamburger:active .bar:nth-child(3){ transform: translateY(-8px) rotate(-45deg); }``` -
Cannot login to django admin page after render deployment
I'm trying to deploy a simple django application (SQLite3) to render but I can't log in to the admin page even with valid superuser credentials. I could authenticate locally, but not while on the render deployed version. Your help is much appreciated! -
Django Update Million of records
i'm new on django, i have a question... is there any method to update million of records at once efficiently in django? *except bulk_update(i have try this but django version 1.11 cannot do this) or transaction.atomic (i have try this method in django, but i want to know others method and still looking for other methods which more efficient) Thanks -
The current path, signup, didn't match any of these in django project
I am using Django for a project but getting following error. It was running perfectly before. I guess, path is not matching in my import. Can I get some hint regarding the path? My directory looks like this: My urls.py looks like this: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('settings', views.settings, name='settings'), path('upload', views.upload, name='upload'), path('follow', views.follow, name='follow'), path('search', views.search, name='search'), path('profile/<str:pk>', views.profile, name='profile'), path('like-post', views.like_post, name='like-post'), path('signup', views.signup, name='signup'), path('signin', views.signin, name='signin'), path('logout', views.logout, name='logout'), Can I get some hint to get rid of this error? Thank you -
How to POST and GET a model with Foreign Key
I am working on a NextJS + Django REST Framework project where I have three models; Document, MySource, and QuestionBlock. Document is created along with several “question_blocks” linked to the created document. They are created together, and I have already implemented this with nested serializers. After the Document is created, I want to be able to POST a MySource model linked to the document. Then, when I make a GET request of a document, all mysource objects should be displayed as well. POST request: notice how I just put the document’s id that I want to link with. { "url": "urlasdf", "title": "tuitle", "publisher": "afdfas ", "desc": "qwefqwef", "summary": "asdfasdf", "document": "J9DY2pE" } GET request: I want the document GET request to show something like below. "id": "LwpQr6Y", "question_blocks": [ { "id": 16, "document": "LwpQr6Y", "title": "question 4", "content": "qweqgadssdffasdf asdf" }, ] "mysource": [ { "id": 16, "url": "google.com", etc. . . }, ], "title": "renamed title", "template": "commonapp", "updated": "2022-05-19T02:16:00+0000", "created": "2022-04-21T06:59:05+0000" The weird part is that I do not see any errors with the code below, and the functionality itself is working properly. But when I attempt to GET the document which has at least one mysource … -
Give access to admin for all branches in Django
I have created a Discussion Forum website where I provide branches to users dynamically. while registration user can select the branch and after login, the user will see only those posts which are related to his selected branch. this functionality works fine for users but when I log in to the admin panel(I have created an admin dashboard where the admin will manage posts and replies. In my case admin is a superuser) an error occurs DoesNotExist at /forum Register matching query does not exist. I know this error comes because I haven't assigned any branch to the admin. But if I will assign any branch to the admin then he will be able to see only a particular branch's posts. But I want the admin can see all branch posts, not a specific branch post. Is there a way to do this if yes please help me to do this model.py Post model class Post(models.Model): user1 = models.ForeignKey(User, on_delete=models.CASCADE, default=1) post_id = models.AutoField post_content = models.TextField(max_length=5000,verbose_name="") timestamp= models.DateTimeField(default=now) branch=models.CharField(default='',max_length=200) image = models.ImageField(upload_to="images",default="") def __str__(self): return f'{self.user1} Post' Reply model class Replie(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) reply_id = models.AutoField reply_content = models.TextField(max_length=5000,verbose_name="") post = models.ForeignKey(Post, on_delete=models.CASCADE, default='') timestamp= models.DateTimeField(default=now) … -
Rate limiting on NGINX grouping by IP address
We are trying to implement a request rate limit on our Django NGINX server. I went through some articles about how to do this, such as https://docs.nginx.com/nginx/admin-guide/security-controls/controlling-access-proxied-http/. I can see that there's the ability to put a specific rate limit on an IP address, and also on a specific "location", that is an API endpoint. But is it also possible to group together some IP addresses and apply a cumulative rate limit. For example, we have a partner that has 5 IP addresses and we want to apply a rate limit of let's say 10 rps on a specific API (/users/), but this 10 rps is a cumulative limit on all the 5 IP addresses, and NOT 10 rps for EACH IP address. I couldn't find on the official NGINX docs or anywhere on Google if this is possible or not. Can anyone help me out please? -
Django Class-Based View With httpresponseredirect
I am trying to add a httpresponseredirect to my class-based CreateView instead of a reverse-lazy, but I am getting errors. Here is my view: class ApplicantCreate(CreateView): model = Applicant success_message = 'Your application was submitted successfully.' form_class = forms.ApplicantForm template_name = 'careers/add_applicant.html' success_url = reverse_lazy('careers:thanks') def form_valid(self, form): context = self.get_context_data() employer = context['employer'] education = context['education'] with transaction.atomic(): form.instance.created_by = self.request.user self.object = form.save() if employer.is_valid(): employer.instance = self.object employer.save() if education.is_valid(): education.instance = self.object education.save() return super(ApplicantCreate, self).form_valid(form) def get_success_url(self): return reverse_lazy('careers:thanks') Thank you for any help. -
command not found: django-admin-version
I'm a beginner in programming. I installed Django, but it shows zsh: command not found: django-admin and zsh: command not found: pip This is my code MacBook-Air ~ % python3 -m pip --version pip 22.1.2 from /Users/myname/Library/Python/3.8/lib/python/site-packages/pip (python 3.8) MacBook-Air ~ % pip list zsh: command not found: pip MacBook-Air ~ % python -m pip install Django zsh: command not found: python MacBook-Air ~ % python3 -m pip install Django Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: Django in ./Library/Python/3.8/bin/django (4.2.dev20220601123622) Requirement already satisfied: asgiref>=3.4.1 in ./Library/Python/3.8/lib/python/site-packages (from Django) (3.5.2) Requirement already satisfied: sqlparse>=0.2.2 in ./Library/Python/3.8/lib/python/site-packages (from Django) (0.4.2) Requirement already satisfied: backports.zoneinfo in ./Library/Python/3.8/lib/python/site-packages (from Django) (0.2.1) MacBook-Air ~ % django-admin --version zsh: command not found: django-admin -
Having additional url under <slug:slug> django
I am trying to add another html webpage on top of a slug:slug url and it throws an error.. i have no idea what went wrong here. Already tried everything i can think of and on the border of giving up, can someone here please help? :) Error message : TypeError at /movies/joker/new/ add_comment() got an unexpected keyword argument 'slug' Request Method: GET Request URL: http://127.0.0.1:8000/movies/joker/new/ Django Version: 4.0.4 Exception Type: TypeError Exception Value: add_comment() got an unexpected keyword argument 'slug' Exception Location: C:\Users\zenmy\PycharmProjects\pythonProject\venv\lib\site-packages\django\contrib\auth\decorators.py, line 23, in _wrapped_view Python Executable: C:\Users\zenmy\PycharmProjects\pythonProject\venv\Scripts\python.exe Python Version: 3.8.0 Python Path: ['C:\\Users\\zenmy\\PycharmProjects\\pythonProject\\Django-IMDB', 'C:\\Users\\zenmy\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip', 'C:\\Users\\zenmy\\AppData\\Local\\Programs\\Python\\Python38\\DLLs', 'C:\\Users\\zenmy\\AppData\\Local\\Programs\\Python\\Python38\\lib', 'C:\\Users\\zenmy\\AppData\\Local\\Programs\\Python\\Python38', 'C:\\Users\\zenmy\\PycharmProjects\\pythonProject\\venv', 'C:\\Users\\zenmy\\PycharmProjects\\pythonProject\\venv\\lib\\site-packages'] Server time: Thu, 02 Jun 2022 06:26:36 +0000 urls.py from django.urls import path from .views import MovieList, MovieDetail, MovieCategory, MovieLanguage, MovieSearch, MovieYear from . import views app_name = 'movie' urlpatterns = [ path('', MovieList.as_view(), name='movie_list'), path('search/', MovieSearch.as_view(), name='movie_search'), path('category/<str:category>', MovieCategory.as_view(), name='movie_category'), path('language/<str:lang>', MovieLanguage.as_view(), name='movie_language'), path('year/<int:year>', MovieYear.as_view(), name='movie_year'), path('<slug:slug>', MovieDetail.as_view(), name='movie_detail'), path('<slug:slug>/add-comment/', views.add_comment, name='add-comment'), ] models.py class Movie(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=1000) image = models.ImageField(upload_to='movies') banner = models.ImageField(upload_to='movies_banner', blank=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES, max_length=10) status = models.CharField(choices=STATUS_CHOICES, max_length=2) cast = models.CharField(max_length=100) year_of_production = models.DateField() views_count = models.IntegerField(default=0) movie_trailer = models.URLField() created = models.DateTimeField(blank=True, … -
How to combine all arguments in two lists if the first element of each list is the same
setting = Subject.objects.annotate(A_setup=Count('id', filter=Q(type='A'), distinct=True) * Value(50), B_setup=Count('id', filter=Q(type='B'), distinct=True) * Value(30), C_setup=Count('id', filter=(~Q(type='A') & ~Q(type='B') & ~Q(type__isnull=True) & Q(id__in=workers.filter(worker=1).values('id')))) * Value(10)) \ .values('setting__user_id', 'A_setup', 'B_setup', 'C_setup') setting = [{'setting__user_id': 4, 'A_setting': 50.0, 'B_setting': 120, 'C_setting': 10.0}, {'setting__user_id': 34, 'A_setting': 0.0, 'B_setting': 0, 'C_setting': 0.0}, {'setting__user_id': 33, 'A_setting': 0.0, 'B_setting': 150, 'C_setting': 0.0}, {'setting__user_id': 30, 'A_setting': 0.0, 'B_setting': 150, 'C_setting': 0.0}, {'setting__user_id': 74, 'A_setting': 50.0, 'B_setting': 120, 'C_setting': 10.0}] uploader = Feedback.objects .values('uploader_id').distinct().values_list('uploader_id') uploader = [{'uploader_id': 25}, {'uploader_id': 20}, {'uploader_id': 74}, {'uploader_id': 34}, {'uploader_id': 93}, {'uploader_id': 88}, {'uploader_id': 73}, {'uploader_id': 89}, {'uploader_id': 30}, {'uploader_id': 33}, {'uploader_id': 85}, {'uploader_id': 4}, {'uploader_id': 46}] "setting" outputs only users who satisfy the conditions. But I need a list of all users. The "uploader" is a queryset containing all users. First, the entire list of users is printed, and if the user's id is included in the "setting", the setting value is output. The final result I want to achieve is as follows. Desired Result: [['25', '0', '0', '0'], ['20', '0', '0', '0'], ['74', '50', '120', '10'], ['34', '0', '0', '0'], ['93', '0', '0', '0'], ['88', '0', '0', '0'], ['73', '0', '0', '0'], ['89', '0', '0', '0'], ['30', '0', '150', '0'], ['33', '0', '150', '0'], … -
Jquery not loading from static files
This is my project structure: pack ├── mysite │ ├── blog │ │ ├── admin.py │ │ ├── apps.py │ │ ├── __init__.py │ │ ├── migrations │ │ ├── models.py │ │ ├── __pycache__ │ │ ├── tests.py │ │ └── views.py │ ├── db.sqlite3 │ ├── manage.py │ ├── mssql_app │ │ ├── admin.py │ │ ├── apps.py │ │ ├── forms_old.py │ │ ├── forms.py │ │ ├── __init__.py │ │ ├── migrations │ │ ├── models.py │ │ ├── models.txt │ │ ├── __pycache__ │ │ ├── routers.py │ │ ├── templates │ │ ├── tests.py │ │ ├── urls.py │ │ ├── views_old.py │ │ └── views.py │ ├── mysite │ │ ├── __init__.py │ │ ├── __pycache__ │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ └── static │ ├── admin │ └── js └── venv In settings.py there is: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'mysite/static') ] STATIC_ROOT = os.path.join(BASE_DIR, "static/") I'm trying to load jquery in /pack/mysite/mssql_app/templates/base.html as follows: {% load static %}<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <title>{% block title %}Packing{% endblock %}</title> </head> But … -
how can I avoid time out in django
I am creating a site that downloads videos from other sites and converts them to GIF when requested. The problem is that it takes too long to download and convert videos. This causes a 504 timeout error. How can I avoid timeout? Currently, I am downloading using celery when we receive a request. While downloading, django redirects right away. def post(self, request): form = URLform(request.POST) ctx = {'form':form} .... t = downloand_video.delay(data) return redirect('gif_to_mp4:home') This prevents transferring the files to the user. Because celery cannot return file to user or response. How can I send the file to the user? -
My django website is having trouble getting deployed on heroku
I have been trying to deploy a website that has already been made to Heroku; however, many errors keep appearing one of them being Running python3 manage.py collectstatic on ⬢ semipreneurs... up, run.2334 (Free) Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 386, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 87, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 74, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 183, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "/app/Semientrepreneurs/settings.py", line 181, in <module> MIDDLEWARE.insert(1, 'whitenoise.middleware.WhiteNoiseMiddleware') AttributeError: 'tuple' object has no attribute 'insert' However, I do not have that many lines in my settings.py file making it impossible to find the place of the error. Settings.py - """ Django settings for Semientrepreneurs project. Generated by 'django-admin startproject' using Django 4.0.1. For more information on …