Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Sorting data / refresh page with new query - Django5 ListView
I am trying to perform a query on the same page using Django. After selecting data from the dropdown and clicking the button, the information should be filtered accordingly. However, I couldn't find a solution to get the data after selecting from my dropdown and will refresh the page using Django. Is this possible? Here's my views.py class DocListView(ListView): model = Document template_name = 'docs/documents.html' paginate_by = 5 context_object_name = 'doc_list' def get_queryset(self): return Document.objects.all() -
Issue with Azure "django_auth_adfs" and Django built in Token Authentication (IsAdminUser)
I have a Django web app with built in Django Rest Framework. I would like to use the Api via Powershell script to update/create data on the database. The Web application will be accessed by users and they will authenticate via Microsoft login. Currently the authentication works fine, but I'm not able to post to database via Powershell using the token that I created within the Django Admin Portal (Admin User). I get a 401 UNAUTHORIZED. I can confirm the token is generated using Super user account. The api works when I remove permission_classes = [IsAdminUser] from the DRF Create View. When I don't exempt the API url and tries to Post it take me to Microsoft login page and if I exempt the url , I get an authorized call error. In short please guide me on how I can do a post request to a specific endpoint without logging or providing credentials, but just using token. I want to user Azure Authentication in conjunction with Django DRF token authentication. This the guide I referred for ADFS authentication - https://django-auth-adfs.readthedocs.io/en/latest/install.html Below is my settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-xxxx' DEBUG = True … -
Django unit test issue with thread and database interaction : database is being accessed by other users
I have a Django project with the following View : def base_task(): # do something def heavy_task(): # do something with interaction with a PostgreSQL database class MyView(generics.UpdateAPIView): def update(self, request, *args, **kwargs): message_to_return, heavy_task_needed = base_task() if heavy_task_needed thread = Thread(target=heavy_task) thread.start() return JsonResponse(message_to_return, status=201) This code returns a response to the client as fast as possible, and start some heavy processing on another thread. I have some unit tests for this code : class EndpointsTestCase(TestCase): fixtures = ["segment.json", "raw_user.json"] def test_1(self): c = Client() body = { #some data } response = c.put( path=f"/my/endpoint/", data=json.dumps(body), content_type="application/json", ) expected_body = to_json_comparable({ #some data }) self.assertEqual(response.content, expected_body) def test_2(self): c = Client() body = { #some data } response = c.put( path=f"/my/endpoint/", data=json.dumps(body), content_type="application/json", ) expected_body = to_json_comparable({ #some data }) self.assertEqual(response.content, expected_body) The issue I have is that, if multiple test cases trigger the heavy_task thread, my tests fail with this error : django.db.utils.OperationalError: database "my_db" is being accessed by other users DETAIL: There are X other sessions using the database. Likely due to the fact that a new test has been started before the thread of the previous test has terminated. How can I solve this issue, as … -
phone number and password not storing in the django admin
Hello I was trying to make a project and the phone number and password from the signup page is not storing but other things like name email are being registered.I tried checking it so many times but could not figure it out ` customer model `from django.db import models from django.core.validators import MinLengthValidator class Customer(models.Model): first_name = models.CharField(max_length=50, null=True) last_name = models.CharField(max_length=50, null=True) phone = models.CharField(max_length=15, null=True) email = models.EmailField(default="",null=True) password = models.CharField(max_length=500,null=True) def register(self): self.save() @staticmethod def get_customer_by_email(email): try: return Customer.objects.get(email=email) except: return False def isExists(self): if Customer.objects.filter(email = self.email): return True return False` views \`from django.shortcuts import render, redirect from django.http import HttpResponse from .models.product import Product from .models.category import Category from .models.customer import Customer def signup(request): if request.method == 'GET': return render(request, 'core/signup.html') else: postData = request.POST first_name = postData.get('firstname') last_name = postData.get('lastname') phone = postData.get('phone') email= postData.get('email') password =postData.get('password' ) customer= Customer(first_name= first_name, last_name= last_name, phone=phone, email=email, password= password) customer.register() return redirect('core:homepage') -
How to translate default Django admin panel to another language?
I use the default Django admin panel with jazzmin. I need the entire admin panel to be completely in Turkmen language. As far as I know, it is not supported in Django yet. How can I translate the entire admin panel to Turkmen? I tried to include these: from django.contrib import admin admin.site.index_title = "SmartLib" admin.site.site_header = "SmartLib Dolandyryş" admin.site.site_title = "Dolandyryş" But it is not enough. I need to translate everything. I also tried makemessages and compilemessages but they didn't generate .po files from the admin panel. -
Google Cloud Storage URL stripped from deployed build/index.html in Django/React on Google Cloud Run (GCR)
Here's the situation. I deploy a Django/React app to Google Cloud Run (GCR) with Docker and static files served over Google Cloud Storage (bucket) Everything is fine except a thing I haven't managed to figure out and I did so many trials that it's impossible to tell my attempts. I'm pretty sure the bucket and GCR service accounts are correct and have sufficient permissions. All necessary API's are activated. The command python manage.py collectstatic run in entrypoint.sh works and the files are uploaded correctly to the bucket. Also, I am totally new to this coming from a "classic" Full Stack PHP/MySQL/JS development environment. Here's the issue. When I run npm run build the /build/index.html shows the correct url to the static files (js/css) like so: src="https://storage.googleapis.com/my-app-bucket/staticfiles/static/js/main.xxx.js" When deployed it "strips" the main url part leaving /staticfiles/static/js/main.xxx.js and so it tries to call the files with the app url like so https://default-xxxxx.a.run.app/staticfiles/static/js/main.xxx.js which of course produces a 404. How can I tell my app to get these files from the bucket? Here are the commands I use to deploy: gcloud builds submit --tag us-east1-docker.pkg.dev/my-app/mbd-docker-repo/mbd-docker-image:my-tag and gcloud run deploy default-my-gcr-service \ --image us-east1-docker.pkg.dev/my-app/mbd-docker-repo/mbd-docker-image:my-tag \ --add-cloudsql-instances my-app:us-south1:my-app-db \ --set-secrets=INSTANCE_CONNECTION_NAME=INSTANCE_CONNECTION_NAME:1 \ --set-secrets=INSTANCE_UNIX_SOCKET=INSTANCE_UNIX_SOCKET:1 \ --set-secrets=DB_NAME=DB_NAME:3 … -
Check if the id is present in the JsonField(list) passed to OutRef during Django subquery filtering
If I have 2 models related through a JsonField(list),I am annotating a queryset of Foos with bars in this list class Foo(Model): bar_list = models.JSONField(default=list) class Bar(Model): id = IntegerField() bar_query = Bar.objects.filter(id__in=OuterRef('bar_list')).values("id")[:1] foos_with_bar_id = Foo.objects.all().annotate(task_id=Subquery(bar_query)) but it doesn't work. I get a error"django.db.utils.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near..." But when i relplace the "OuterRef" to a specified list, like[1,2,3], It works. So does OuterRef not support JsonField? -
what's (page = DEFAULT_PAGE) role in CustomPagination by DRF (django-rest-framework)?
For some reason, I could not understand the meaning and role of page=DEFAULT_PAGE in Custom Pagination in the DRF topic. Can you explain its role to me in the code below? Consider - pagination.py: from rest_framework.pagination import PageNumberPagination from rest_framework.response import Response DEFAULT_PAGE = 9 DEFAULT_PAGE_SIZE = 9 class CustomPagination(PageNumberPagination): page = DEFAULT_PAGE page_size = DEFAULT_PAGE_SIZE page_size_query_param = 'page_size' def get_paginated_response(self, data): return Response({ 'links': { 'next': self.get_next_link(), 'previous': self.get_previous_link() }, 'total': self.page.paginator.count, 'page': int(self.request.GET.get('page', DEFAULT_PAGE)), # can not set default = self.page 'page_size': int(self.request.GET.get('page_size', self.page_size)), 'results': data }) Note : This is important to me for setting up my app and I wanted to understand its role... Although I consulted the documentation, I didn't understand much about the role of page=PAGE_DEFAULT. -
override save for model so only one value is possible
I want to handle a unique condition on the save method of the model: class Car(models.Model): fuel = models.CharField("type of gasoline", max_length=256, null=True, blank=True) charger = models.CharField("loading plug type", max_length=256, null=True, blank=True) def save(self, *args, **kwargs): if self.charger: self.fuel = None elif self.fuel: self.charger = None super().save(*args, **kwargs) Desired behavior: When loading a Car instance and setting fuel="diesel" I want charger=None set automatically on save(). -
What is another way to implement apple sign-in in a django API project without creating an apple developer profile?
Apple bills $99 to create a developer profile. Is there a way to override that step in implementing apple sign-in in my django project ? I tried implementing apple sign in and was expecting to create a free developer profile but unfortunately, I was asked to pay the sum of $99 -
Django numerical RangeField (for SQLite)
After reading the docs for custom model fields of Django 5.0 I'm not sure if or how it's possible to create a ModelField that resembles a range between two numerical (integer) values, since I can only serialize into a single db_column, not into two (min of range, max of range column). Am I wrong? Is there a possibility I don't see? I know for PostgreSQL there are different RangeFields available. -
Dj-rest-auth "CSRF Failed: CSRF token missing"
When I am trying to post data using my dj-rest-auth api http://localhost:8000/dj-rest-auth/login/ it gives this error CSRF Failed: CSRF token missing. How do I fix this as I am unable to find the CSRF value to put into headers. Where can I actually find this value. This is my settings for dj-rest-auth in views.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', 'dj_rest_auth.jwt_auth.JWTCookieAuthentication', ), } REST_AUTH = { 'USE_JWT': True, 'JWT_AUTH_COOKIE': 'jwt-auth', } EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' SITE_ID = 1 ACCOUNT_EMAIL_REQUIRED = False ACCOUNT_AUTHENTICATION_METHOD = 'username' ACCOUNT_EMAIL_VERIFICATION = 'optional' AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by email 'allauth.account.auth_backends.AuthenticationBackend', ] Tried sending a get request to this api but the method isn't allowed Tried putting the csrf value of localhost:8000 in my headers which I got from mozilla firefox in the storage/cookies section. But it said the csrf value is incorrect. -
How to handle - Error in save method in Django Model
This is my model: class Sale2021(models.Model): Id = models.AutoField(primary_key=True) cust_name = models.CharField(max_length=120) class= models.CharField(max_length=120) cust_id = models.CharField(max_length=120) branch_desc = models.CharField(max_length=120) cust_desc = models.CharField(max_length=120) month_year = models.CharField(max_length=120) distance_in_kms = models.CharField(max_length=120) def save(self, *args, **kwargs): # Use the get_or_create method with your unique identifier(s) obj, created = Sale2021.objects.get_or_create( cust_id=self.cust_id, month_year=self.month_year, defaults={ 'cust_name ':self.cust_name, 'class':self.class, 'cust_id ':self.cust_id, 'branch_desc':self.branch_desc, 'cust_desc':self.cust_desc, 'distance_in_kms':self.distance_in_kms, }) if created: # If the object is newly created, save it as usual super(Sale2021, self).save(*args, **kwargs) else: # If the object already exists, update its fields obj.cust_name=self.cust_name obj.class=self.class obj.cust_id=self.cust_id obj.branch_desc=self.branch_desc obj.cust_desc=self.cust_desc obj.month_year=self.month_year obj.distance_in_kms=self.distance_in_kms obj.save() I want if the customer adds a new row in the database, I want to check where there is a row with same cust_id and month_year fields. If yes, then update the existing row, else create one. When I trying to add a new row, I'm getting this error: RecursionError at /admin/home/sale2021/add/ maximum recursion depth exceeded Request Method: POST Request URL: http://127.0.0.1:8000/admin/home/sale2021/add/ Django Version: 5.0 Exception Type: RecursionError Exception Value: maximum recursion depth exceeded Exception Location: C:\Users\Dell\AppData\Local\Programs\Python\Python312\Lib\copyreg.py, line 99, in __newobj__ Raised during: django.contrib.admin.options.add_view Python Executable: C:\Users\Dell\AppData\Local\Programs\Python\Python312\python.exe Python Version: 3.12.1 Python Path: ['C:\\Users\\Dell\\Desktop\\KESORAM\\12-01-2024\\dj_web\\dj_web', 'C:\\Users\\Dell\\AppData\\Local\\Programs\\Python\\Python312\\python312.zip', 'C:\\Users\\Dell\\AppData\\Local\\Programs\\Python\\Python312\\DLLs', 'C:\\Users\\Dell\\AppData\\Local\\Programs\\Python\\Python312\\Lib', 'C:\\Users\\Dell\\AppData\\Local\\Programs\\Python\\Python312', 'C:\\Users\\Dell\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages'] Server time: Fri, 12 Jan 2024 06:44:58 +0000 This line … -
Does not log in to the account through the socialaccount in Django allauth
Does not log in to the account through the socialaccount, although the message appears 'Successfully signed in as ' ({% if user.is_authenticated %} is False, user is AnonymousUser). Everything is configured according to the instructions in the documentation. Simple accounts (via login and password) are logged in ({% if user.is_authenticated %} is True). I've tried different providers, different ways to add keys, and used settings that could have an impact. But nothing helped. Please help me understand how to set up allauth so that logging in only through the social account is carried out. -
How to align each new post next to each other?
I am working on this blog and I want to whenever a user makes a new post it gets displayed next to the others not under them but I don't know what should I do so far I have these cards but they keeps being displayed under each other if I need to post another part of my code please let me know I appreciate the help I want it to be something like this post.html {% extends "online_shop/base.html" %} {% load static %} {% block content %} {% for post in posts %} <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div style="margin-top: 35px;"></div> <div class="card-deck" style="max-width: 300px;"> <div class="card row"> <img class="card-img-top" src="{% static 'online_shop/unicorn-cake-14.jpg'%}" alt="Card image cap" width="300" height="310"> <div class="card-body"> <h2><a class="article-title" href="#">{{ post.title }}</a></h2> <p class="card-text">{{ post.content }}</p> {{ post.content|truncatewords_html:15 }} </div> <div class="card-footer"> <small class="text-muted"><a href="#">{{ post.author }}</a></small> <small class="text-muted" style="margin-left: 5px;">{{ post.date_posted|date:"F d, Y" }}</small> </div> </div> </div> </body> {% endfor %} {% endblock content %} -
is there a way to upload multiple large image files to GCS in django admin?
I'm attempting to upload multiple image files to a Google Cloud Storage bucket simultaneously through the django admin interface, 14 image files totaling up to 175mb. They are contained in one model with multiple imagefields. I'm using django-storages to connect django to gcs. I'm not able to increase the upload timeout past the 10 minute mark, and I have to stay inside the django admin interface. My project lead suggested that there might be a way to split the POST request into multiple smaller requests to circumnavigate the timeout, but I can't find any documentation on how to do such a thing inside django admin. Clicking 'save' creates a POST request that takes over 10 minutes, which is long enough to give me a 413 error. I'm using google app engine as a back-end. When I use the local test server, it all uploads as intended. It takes a little while but not ten minutes. If I save after changing one or two images at a time it uploads successfully. -
Inapp mail service django and reactjs
I am making some school management system in django and reactjs ,I want help in making inmail system so that teacher can send notice/attachment to the student of his/her class at once and it will be oneway communication. I wanted to build this but don't have any idea what technology to be use in django . If anyone know the approach than please reply Thanks -
Not able to display image uploaded using django
I was able to upload image using views and templates in django but was not able to display those images. I could only display images stored in static folder but not from the media folder or any other location. I have done all the steps mentioned in docs and in other solution but this is not working for me. I created a model which looks like class Product(models.Model): image = models.ImageField(upload_to='product_images/') description = models.TextField(null=True) quantity = models.IntegerField(null=True) and my forms.py is class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['image', 'description', 'quantity'] my views.py is like this @login_required def display_products(request): products = Product.objects.all() return render(request, 'farmer/display_products.html', {'products': products}) @login_required def upload(request): if request.method == "GET": form = ProductForm() if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('display_products') return render(request, 'farmer/my_products.html', {'form': form}) my file is like this {% load static %} {% for product in products %} <div class=""> <h2>{{ product.name }}</h2> {{product.image.url}} image: <img src="static/dry.jpeg" alt="sample"> <p>description: {{ product.description }} quantity: {{ product.quantity }} </p> </div> settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ BASE_DIR / 'static/css', ] LOGIN_URL = 'login' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') DEBUG = True urls.py if settings.DEBUG: urlpatterns … -
loops in Django template
on my template, i have 3 pictures from products in my database i'm trying to loop through. the goal is to display in one div, the pictures of products that are marked available, and in another div, pictures of products that are not marked available. using the code below does not show any items that do not have the same availability as product1. but it shows the pictures of product1 in its appropriate div, as i switch it's availability. i don't know why this is happening, please help. ''' my model looks like class Product(ModelMeta, models.Model): user = models.ForeignKey(User, default=1, null=True,on_delete=models.SET_NULL) title = models.CharField(max_length=120) available = models.BooleanField(default=True) class SiteImage(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,null=True) object_id = models.PositiveIntegerField(null=True) content_object = GenericForeignKey('content_type', 'object_id') image = models.ImageField(upload_to='image/', blank=True, null=True) caption = models.CharField(max_length=50, blank=True) my view looks like def home_page(request): pictures = SiteImage.objects.filter(content_type__model='product') testimonials = Testimonials.objects.all() context = {'pictures': pictures,} return render(request, 'home.html', context) my template looks like {% for picture in pictures %} {% if picture.content_object.available %} {{ picture.product.title }} {{ picture.caption }} {% endif %} {% endfor %} {% for picture in pictures %} {% if not picture.content_object.available %} {{ picture.product.title }} {{ picture.caption }} {% endif %} {% endfor %} ''' -
Django annotate method with when clouse using query key as a Value
I need to add ordering_datetime column when field=field matches. And for a Value I want to get it from "date_time_value" field. queryset = queryset.annotate( ordering_datetime=Case( When( field=field, then=Value("date_time_value") ), output_field=DateTimeField(), ) ).order_by("pk", f"{order_lookup}ordering_datetime").distinct("pk") how to get value from column that matches field=field rows. when I tried to give the column name directly as a value doesn't work. It expects a static value, not a query key -
Angular CLI Proxy + Django Backend not working with Docker
I have an Angular + Django project where I am providing an api to angular with django. When I run the two services separately everything works as expected. When I run both services together using docker compose, angular is suddenly unable to connect to the backend api service. I have seen a similar post on stack but the difference is I am using a single compose file to include two different compose files so I'm not sure how to "link" the backend services to the frontend service like the answers suggest in this post. So what can I do to make this work within docker? Error: [webpack-dev-server] [HPM] Error occurred while proxying request localhost:4200/api/project_types/ to http://api:8000/ [ENOTFOUND] (https://nodejs.org/api/errors.html#errors_common_system_errors) Project Layout: Note: I've dockerized the two services and am using one compose file in the root folder to include both the backend and frontend compose files. - root - backend - backend-compose.yml - frontend - frontend-compose.yml - docker-compose.yml Root Compose: version: '3.7' include: - ./frontend/compose.yml - ./backend/local.yml Frontend Compose: services: web: build: context: . target: builder ports: - 4200:4200 volumes: - ./angular:/app - /project/node_modules Backend Compose: (Note: built with cookiecutter django) version: '3' volumes: backend_local_postgres_data: {} backend_local_postgres_data_backups: {} services: django: build: … -
pytest-django : Invalid choice in client.post
If I print theme_1 in the begining or at the end of the test i get the theme_1 object. But theme_1 in client.post is... None ! I don't understand.. :s Can you help me ? Thank you :) @pytest.fixture def theme_1(db): return Theme.objects.create(name="dev") @pytest.mark.django_db def test_create_forum_view_post(client: Client, theme_1, user_1): client.login(username=user_1.username, password="12345678") response = client.post(reverse("forum:create-forum"), data={"name": "devforum", "theme": theme_1, "description": "Forum des devs"}) form = response.context["form"] print(form.errors) print(response) -
Choosing between Polymorphic Associations and Separate Tables
I'm working on a Django project where I need to manage generic attachments across different entities in my system. Currently, I'm using a polymorphic model as follows: class AttachmentGenericModel(BaseModel): content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True, blank=True) object_id = models.UUIDField(null=True, blank=True) content_object = GenericForeignKey('content_type', 'object_id') file = models.FileField(upload_to=upload_to_path) class ProblemStatement(BaseModel): context = models.TextField() files = GenericRelation(AttachmentGenericModel) class Proposal(BaseModel): files = GenericRelation(AttachmentGenericModel) However, I'm wondering if it's preferable to use separate tables for each entity, like ProposalFile, ProblemStatementFile, etc. My concern is that the main table AttachmentGenericModel may become complex over time as the number of entities involved grows. I'm curious if anyone has experiences or advice on which approach is more advantageous in terms of performance, maintainability, and scalability. Additionally, what considerations should be taken into account when deciding between polymorphic associations and separate tables for handling generic attachments in Django? As an illustrative example, here's an example with separate tables: class ProblemStatementFile(BaseModel): problem_statement = models.ForeignKey(ProblemStatement, on_delete=models.CASCADE) file = models.FileField(upload_to=upload_to_path) class ProposalFile(BaseModel): proposal = models.ForeignKey(Proposal, on_delete=models.CASCADE) file = models.FileField(upload_to=upload_to_path) What are the pros and cons of each approach, particularly in a future scenario where numerous new tables with file relationships may be needed? Thank you in advance for your valuable insights! -
Making a Highest Rated Albums List Based on Ratings Averages from Two Models
I have an Album model (shortened for space): class Album(models.Model): creator = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) artist = models.CharField(max_length=255) title = models.CharField(max_length=255) rating = models.IntegerField( choices=[(i, i) for i in range(1, 11)], validators=[MaxValueValidator(10), MinValueValidator(1)], default=10, ) comment = models.TextField(null=True, blank=True) And a Review model (again, shortened for space): class Review(models.Model): reviewer = models.ForeignKey(User, on_delete=models.CASCADE, null=True) album = models.ForeignKey(Album, on_delete=models.CASCADE) rating = models.IntegerField( choices=[(i, i) for i in range(1, 11)], validators=[MaxValueValidator(10), MinValueValidator(1)], default=10, ) comment = models.TextField() The Album model is for users to create an Album and add their initial review and rating. The Review model is for users to be able to add a review to an existing album, and also a rating. I have this model method attached to the Album in order to create an average rating to display in templates: def avg_rating(self): review_ratings = 0 orig_rating = self.rating review_ratings_count = self.review_set.count() if review_ratings_count > 0: for review in self.review_set.all(): review_ratings += review.rating ratings_sum = review_ratings + orig_rating ratings_count = review_ratings_count + 1 ratings_avg = ratings_sum / ratings_count avg_return = round(ratings_avg, 1) if avg_return == 10.0: avg_return = 10 else: avg_return = avg_return return avg_return else: return self.rating Sadly, avg_rating cannot be used (to my knowledge) in … -
raise ValueError, "No frame marked with %s." % fname. SyntaxError: invalid syntax at import environ in settings.py file
When building a docker container with the --platform=linux/amd64 python:3.9 image, I encounter an error: Traceback (most recent call last): File "/var/www/myapp/manage.py", line 22, in <module> main() File "/var/www/myapp/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 69, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.9/site-packages/django/conf/__init__.py", line 170, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/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 "/var/www/newapp/myapp/settings.py", line 2, in <module> import environ File "/usr/local/lib/python3.9/site-packages/environ.py", line 114 raise ValueError, "No frame marked with %s." % fname ^ SyntaxError: invalid syntax I tried the recommended change to python3 -m pip install requirements.txt/pip3 install requirements.txt in the Dockerfile but nothing worked. The build of my container still exited with an error. What I realised is that the django-environ package as included in the requirements.txt file was either not installed or the absence of …