Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Log accesses to Django model fields?
I have a Django model with 100+ fields, and would like to log which fields are being used to clean up the model. For example, which fields are used when running Person.objects.get(person_id=123). -
Django Template: Concatinate a string and format a date
Inside Django Template, how can I concat a variable that has a formatted date? I'm trying to create a button to redirect to another page. When I do this, it gives me an error because of the quotation marks: <input type="button" class="btn btn-primary" onclick="location.href='/print_receipts?u={{ username }}&mpu=t&pst={{ pantry_start_time|date:'G:i:s' }}&pantry_end_time={{ pantry_end_time|date:'G:i:s' }}&dow={{ dow }}'" value="Mark as Picked Up" /> So I thought I can concat the string and variables, but it didn't work when I try to format the date for pantry_end_time or pantry_start_time. {% with link="/print_receipts?u={{ username }}&mpu=t&pst={{ pantry_start_time|date:'G:i:s' }}&pantry_end_time={{ pantry_end_time|date:'G:i:s' }}&dow={{ dow }}" %} <input type="button" class="btn btn-primary" onclick="location.href='{{ link }}'" value="Mark as Picked Up" /> link: {{ link }} {% endwith %} -
Django get all field after group by one field
I have a model: class AccessConfigFile(models.Model): file_name = models.CharField(unique=True, max_length=200, default=None) class AccessConfig(models.Model): file = models.ForeignKey(AccessConfigFile, on_delete=models.CASCADE, default=None) data = models.CharField(verbose_name='ems data', default='', blank=True, max_length=50000) version = models.IntegerField(default=0) I want to get data of latest version of each file for AccessConfig model. I have a query: AccessConfig.objects.values('file').annotate(version=Max('version')) But it just got 2 fields file and version. How can I get all fields with MySQL DB? Because MySQL can not use distinct('field_name') function as PostgreSQL -
How to set the vice versa condition for django models
I am using Django3 and model I want to get the data of Distance from one city to another city. But in the database, only the distance A to B is stored ( because distance of B to C is the same) So, what I want to is fetch the correct row, regardless the order of cities. I can do this with use these two sentences and error check each. Distance.objects.get(key_first=firstcity, key_second=secondcity) Distance.objects.get(key_second=secondcity, key_second=firstcity) However it looks a bit awkward and it requres two times DB fetch, Is there any smarter way like this below?? Distance.objects.get((key_first=firstcity, key_second=secondcity) | (key_second=secondcity, key_second=firstcity)) -
How to serve quasar dist files from django?
I have used python manage.py collectstatic to collect the quasar dist files generated after the quasar build command. But I am getting the following error. http://127.0.0.1:8000/static/js/vendor.df0d9f8a.js net::ERR_ABORTED 404 (Not Found)... Here are my djnago index.html code from where I am calling the js and css from the static folder. {% extends "base.html" %} {% load static %} {% block style %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link href="{% static 'css/vendor.187160a9.css' %}" rel=stylesheet> <link href="{% static 'css/app.0e433876.css' %}" rel=stylesheet> {% endblock %} {% block content %} <noscript> <strong>We're sorry but frontend doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"></div> {% endblock %} {% block js %} <script src=https://cdn.jsdelivr.net/jsbarcode/3.3.20/JsBarcode.all.min.js></script> <script type="text/javascript" src="{% static 'js/vendor.df0d9f8a.js' %}"></script> <script type="text/javascript" src="{% static 'js/app.ba927e14.js' %}"></script> {% endblock %} Is there any other approach to serve quasar dist files from django? -
Автодополнение оставшихся полей в vue.js [closed]
Есть проект с фронтом на vue и бэком на джанго,нужно при вводе в одно поле проверять значение и вызывать функцию с этим значением,и в реальном времени обновлять оставшиеся поля инпутов значениями полученныеми из функции,но с возможностью последующего редактирования -
How to create directories/files on the local machine using Django?
I'm working on a blockchain project where I'm implementing a wallet using Django. A user logs in and get's to generate an address. Now, I want to store the user's private key/public key pair in a file locally on the user's machine every time a user generates an address, and be able to read that file again in the next session (at the user's will). I'm doing this because the app itself is a supernode of the blockchain and all users are virtual nodes. All communication between users happen through the supernode, thus the wallet functionality isn't the core function of the app. Everything is working perfectly except I can't find a way to create files locally on the client's machine. I've perused the Django documentation but I can't seem to find anything useful (maybe I'm not looking in the right place). Is there a way I can achieve that? Note: I'm trying as much as possible to avoid JavaScript, and I don't want users to download/upload files manually. -
serializer field error on serializer method field
i am trying to customer name and meter number on my customer report serializer , but i am getting below-mentioned error, i am going as Docs but don't know what seems to be the issue class CustomerReportSerializer(serializers.HyperlinkedModelSerializer): meter_no = serializers.SerializerMethodField(method_name='get_meter_num') customer_name = serializers.SerializerMethodField(method_name='get_cust_name') class Meta: model = CustomerReport fields = ['meter_no','meter','customer_name','date','customer_unit','unit_rate','bill_amount',] def meter_num(self,obj): if obj.meter.number: return obj.meter.mumber else: return "" def cust_name(self,obj): if obj.meter.customer.name: return obj.meter.customer.name else: return "" class CustomerReport(models.Model): meter = models.ForeignKey('Meter', on_delete=models.CASCADE) date = models.DateTimeField(auto_now=True) customer_unit = models.IntegerField() unit_rate = models.DecimalField(decimal_places=2, max_digits=10) bill_amount = models.DecimalField(decimal_places=2, max_digits=10) def __str__(self): return str(self.meter.customer) 'CustomerReportSerializer' object has no attribute 'get_meter_num' -
need id's of objects from Django query where customer id's are distinct and unique
CfgXmppSessions.objects.filter(character_objid=9100).values_list('customer_objid').annotate(objiod1=F('objid')).distinct()) I want all objid where customers are unique -
Serializer extra field from a ManyToMany Field
I have these serialiazers class DepartmentSerializer(serializers.ModelSerializer): class Meta: model = Department fields = ('name', 'slug', 'image', 'description') class DoctorSerializer(serializers.ModelSerializer): class Meta: model = Doctor fields = '__all__' depth = 1 and the current representation is like this: { "id": 1, "first_name": "Jhon", "last_name": "Doe", "slug": "jhon-doe", "email": null, "phone": null, "title": null, "description": "", "image": "http://localhost:8000/media/studio/default.jpg", "department": [ { "id": 1, "name": "Acupuncture", "slug": "Acupuncture", "image": "http://localhost:8000/media/studio/acupuncture-min.jpg", "description": "Acupuncture" }, { "id": 3, "name": "Cardiology", "slug": "cardiology", "image": "http://localhost:8000/media/studio/default.jpg", "description": "Cardiology" } ] } I'd like to keep the department field as IDs and have an extra field for departmentName and have a representation like this: { "id": 1, "first_name": "Jhon", "last_name": "Doe", "slug": "jhon-doe", "email": null, "phone": null, "title": null, "description": "", "image": "http://localhost:8000/media/studio/default.jpg", "department": [ 1, 3 ] "departmentName": [ { "id": 1, "name": "Acupuncture", "slug": "Acupuncture", "image": "http://localhost:8000/media/studio/acupuncture-min.jpg", "description": "Acupuncture" }, { "id": 3, "name": "Cardiology", "slug": "cardiology", "image": "http://localhost:8000/media/studio/default.jpg", "description": "Cardiology" } ] } This is because if I have the 1st representation I have problems in managing the CRUD because department are not IDs. The problem is because department is a ManyToMany relation, for example if it was just a ForeignKey I could have done … -
Auto Attribute completetion Not working at Django-HTML at vs code
Attribute completion or attribute IntelliSense not working. When I write code on an Html file, vs code suggest me attribute name, for example: if I type cl then vscode suggests me class="". this is a great feature for saving time. but when I gonna writing code on Django-HTML. this feature was not working. I tried to find the solution to this problem. but I can't. Please help me. Please tell me how can I get this auto attribute completion feature on the Django template. which is Django-html. -
How to filter product by its Attribute in Django - Django?
I'm working on a Django Ecommerce project where product has several attributes like. size, color( A single product can have multiple attributes with different size and color). No i'm trying to filter products using django_filters but unable to filter by its attributes. Below are the codes(models) for your reference. Request you to kindly look in to and help. Thanks in advance. Product Model: class Product(models.Model): variations = ( ('None', 'None'), ('Size', 'Size'), ) name = models.CharField(max_length=200, unique=True) store = models.ManyToManyField(Store) slug = models.SlugField(null=True, blank=True, unique=True, max_length=500) sku = models.CharField(max_length=30, null=True) tax = models.IntegerField(null=True, blank=True) stock = models.CharField(max_length=10, null=True) variations = models.CharField(choices=variations, max_length=20) short_description = models.CharField(max_length=500, null=True) details = RichTextUploadingField(null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) discounted_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) image = models.ImageField(upload_to='product/images', default='product.png', null=True, blank=True) image_one = models.ImageField(upload_to='product/images', null=True, blank=True) image_two = models.ImageField(upload_to='product/images', null=True, blank=True) image_three = models.ImageField(upload_to='product/images', null=True, blank=True) image_four = models.ImageField(upload_to='product/images', null=True, blank=True) image_five = models.ImageField(upload_to='product/images', null=True, blank=True) tags = models.ManyToManyField(Tags) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True, related_name='products') status = models.CharField(max_length=20, choices=(('Active', 'Active'), ('Inactive', 'Inactive'))) brand = models.ForeignKey(Brand, on_delete=models.PROTECT, blank=True, null=True) offer = models.ForeignKey(Offer, on_delete=models.CASCADE, null=True, blank=True) # This is used only for filtration Product attribute model class ProductAttribute(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) size = models.ForeignKey(Size, on_delete=models.CASCADE, … -
django set_cookie does not set cookie in browser
I am writng a drf app, that sets cookie. I set cookie like this: serializer = TitleSerializer(result.titles, many=True) response = JsonResponse(serializer.data, safe=False) response.set_cookie("country_code", code) return response But when I check request for cookies like this: if 'country_code' in request.COOKIES: print(request.COOKIES['country_code']) I get nothing. I checked response object in browser console and it has them in headers: Set-Cookie country_code=unknown; Path=/ and in cookies: country_code path "/" value "unknown" But when I go to inspect>storage>cookies there is nothing there. Should I set cookies by hand in js or am I doing something wrong in django part? I just googled how to set cookies in django and it seemed like browser should set and send cookies automaticly, so I was curious what I'm doing wrong. -
Django .exclude() returns empty queryset
I have a problem with .exclude() when making a QuerySet. My models involved are: Profession class Profession(models.Model): profession_name = models.CharField(max_length=20) equipment = models.ManyToManyField(Equipment, blank=True) ability = models.ManyToManyField(Ability, blank=True) skill = models.ManyToManyField(Skill, blank=True) skill_advanced = models.ManyToManyField(SkillAdvanced, blank=True) Ability class Ability(models.Model): ability_name = models.CharField(max_length=35) When I create QuerySet with: self.prof_abilities = Profession.objects.filter(profession_name="Acolyte").values('ability') I get: <QuerySet [{'ability': 2}, {'ability': 69}, {'ability': 81}, {'ability': 86}, {'ability': 23}]> But I would like to exclude some values, so I use this instead: self.prof_abilities = Profession.objects.filter(profession_name="Acolyte").exclude(ability__in=[2, 23, 81, 86]).values('ability') But the outcome is an empty QuerySet: <QuerySet []>. I've tried various tweeks like .exclude(ability__id__in=[2, 23, 81, 86]) or .exclude(ability__ability_name__in=['Foo name', 'Bar name'] but with no success. I'm new to Django so if this is something obvious, I would also appreciate some pointers where to read more on my mistake. -
Django rest framework post request returns 200 but data is not saved in the database
when post request is sent to the api, api returns Ok as the response but no data is inserted into the database. views.py @api_view(['POST']) def createTicketList(request): serializer = TicketListSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) serializer.py class TicketListSerializer(serializers.ModelSerializer): class Meta: model = TicketListTable fields = '__all__' def create(self, validated_data): return TicketListTable(**validated_data) models.py class TicketListTable(models.Model): ticketListName = models.CharField(max_length=50) ticketListCreated = models.DateTimeField() ticketListUpdates = models.DateTimeField() def __str__(self): return self.ticketListName class Meta: app_label = "backend" db_table = "TicketListTable" postman api postman api post request -
django getting distinct records in table seems to choose random row
I have a table that contains the pricing data for the cards and I am trying to get the pricing data for distinct cards by card_id but this seems to select the row at random. I would like to get the latest datetime pricing data for each card card_id. Table: id nonfoil foil datetime card_id "fb7fbcdc" 0.20 0.49 "2021-10-11 10:03:51.943603+01" "00302342" "d0d6f491" 0.10 0.49 "2021-10-11 10:01:09.916438+01" "00302342" "bfdca73b" 0.03 0.04 "2021-10-11 10:03:51.907601+01" "012e0b83" "33c7aeae" 0.10 0.04 "2021-10-11 10:01:09.875894+01" "012e0b83" "94ca3324" 0.10 0.04 "2021-10-11 10:01:09.961261+01" "0307f37b" "2e992a8d" 0.03 0.04 "2021-10-11 10:03:51.988602+01" "0307f37b" I currently am getting the pricing data using the following code: pricing_cards.objects.filter(card_id__rarity='mythic').values_list('nonfoil', flat=True).distinct('card_id'), For example this is returning: id nonfoil foil datetime card_id "d0d6f491" 0.10 0.49 "2021-10-11 10:01:09.916438+01" "00302342" "bfdca73b" 0.03 0.04 "2021-10-11 10:03:51.907601+01" "012e0b83" "94ca3324" 0.10 0.04 "2021-10-11 10:01:09.961261+01" "0307f37b" But I would like it to return: id nonfoil foil datetime card_id "fb7fbcdc" 0.20 0.49 "2021-10-11 10:03:51.943603+01" "00302342" "bfdca73b" 0.03 0.04 "2021-10-11 10:03:51.907601+01" "012e0b83" "94ca3324" 0.10 0.04 "2021-10-11 10:01:09.961261+01" "0307f37b" -
Working fine in localhost but page not found when live online in Django
Below are urls.py and views.py part. It was working properly in local host but but return page not found 404 after deployment online. #urls.py from django.urls import path from . import views urlpatterns = [ path('', views.store, name='store'), path('cook/', views.cook, name='cook'), ] #views.py from django.http import HttpResponse def cook(request): return HttpResponse('This is a test message') -
SQL server - Login timeout expired (0) (SQLDriverConnect)
I have created docker container for django application and i wanted to connect with MSSQL in my local machine from the docker but I couldn't able to connect it. I have tried changing the host in the connection string but still its reflecting the same Error which i get when i tried docker-compose up as ERROR-log: conn = Database.connect(connstr, web_1 | pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') settings.py -host i have tried with other ip as well but failed to connect when running in local also DATABASES = { "default": { "ENGINE": "sql_server.pyodbc", "NAME": "dbnew", "USER": "user1", "PASSWORD": "user@1233", # "Integrated Security":"SSPI", "HOST": "172.19.179.179", "PORT": "", "OPTIONS": { "driver": "ODBC Driver 17 for SQL Server", }, }, } dockerfile FROM python:3.8 ENV PYTHONUNBUFFERED 1 WORKDIR /code #before install pyodbc , we need unixodbc-dev # RUN apt-get install multiarch-support # install msodbcsql17 # RUN su RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - RUN curl https://packages.microsoft.com/config/debian/9/prod.list > /etc/apt/sources.list.d/mssql-release.list RUN exit RUN wget http://archive.ubuntu.com/ubuntu/pool/main/g/glibc/multiarch-support_2.27-3ubuntu1.4_amd64.deb RUN apt-get install ./multiarch-support_2.27-3ubuntu1.4_amd64.deb RUN apt-get update # RUN ACCEPT_EULA=Y apt-get install -y msodbcsql17 # RUN 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc # RUN source ~/.bashrc # optional: for unixODBC development headers RUN ACCEPT_EULA=Y … -
Django does not call the function and does not output information from the database
I started learning django recently and am writing a website for a tutor. I need to add output to topics that are entered into the database through the admin panel. But he doesn't take them out. Although the profile data is displayed perfectly. views.py class TopicListView(ListView): model = Topic template_name = 'video/video.html' context_object_name = 'top' def video(request): top = Topic.objects.all() context = {'top': top} return render(request, 'video/video.html', context) video.html {% load static %} <!DOCTYPE html> <html> <head> <link rel="icon" href="../static/images/favicon.jpg" type="image/x-icon"> <link rel="shortcut icon" href="../static/images/favicon.jpg" type="image/x-icon"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Материалы</title> <link rel="stylesheet" href="{% static 'profiles/css/style.css' %}" type="text/css" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script> </head> <body> {% if user.is_authenticated %} <div class="top"> <a href="/">Главная</a> <a class="active" href="video">Материалы</a> <a href="question">Тесты</a> <a href="accounts/logout"> Выйти</a> </div> {% for post in top %} <div> <h3>{{ post.name_topic }}</h3> </div> {% endfor %} {% else %} <p>Ввойдите в профиль, чтобы увидеть эту страницу</p> <div class="button"> <a href="accounts/login">Log in</a> </div> {% endif %} </body> </html> -
problem with same template's name in different app folder in django
I create two folder app1 and app2 by the command startapp. Then I create folder templates in both app1 and app2. In both templates i create a.html but with the different html content. In the views.py of app1 I create a function to render to a.html and when I visit the url of that function, I get the content of a.html of app2 instead of app1. So what happend here? How could I get exactly the html file from app1? My django ver 3.2.8 and python ver 3.9.6 Thanks in advanced. -
I want to get django rest choices key instead of Value
When i select choice for degree type it returns the value of the choice but i want to get key. For example when i select UNFINISHED_BACHELOR from choices it returns Unfinished Bachelor's degree but i want get UNFINISHED_BACHELOR class CandidateEducation(models.Model): class DegreeType(models.TextChoices): HIGH_SCHOOL = "High School" UNFINISHED_BACHELOR = "Unfinished Bachelor's degree" TWO_YEAR = "Two-year degree" degree_type = models.CharField( max_length=100, choices=DegreeType.choices, null=True, blank=True ) degree_title = models.CharField(max_length=100, null=True, blank=True) institution = models.CharField(max_length=100, null=True, blank=True) class CandidateEducationList(generics.ListCreateAPIView): serializer_class = CandidateEducationSerializer queryset = CandidateEducation.objects.all() class CandidateEducationSerializer(serializers.ModelSerializer): class Meta: model = CandidateEducation fields = "__all__" Result: [ { "id": 6, "degree_type": "Unfinished Bachelor's degree", ----> Error "degree_title": "ABC", "institution": "aaa", } ] Expected [ { "id": 6, "degree_type": "UNFINISHED_BACHELOR", "degree_title": "ABC", "institution": "aaa", } ] -
MultiValueDictKeyError at /change-part/. In python django
So i try to make a upload image system, and i make two different type of image, there are static and dynamic and i try to make a different act/function for thoose type, so i made a two if one like this, if len(request.FILES['img_dinamic']) != 0: part = WebPart.objects.get(part=partToChange) if len(part.dinamic_image) > 0: os.remove(part.dinamic_image.path) img_dinamic = request.FILES['img_dinamic'] else: img_dinamic = "" and the other one is like this if len(request.FILES['img_static']) != 0: img_static = request.FILES['img_static'] else: img_static = "" and when i try to run the system, it appears some error like this MultiValueDictKeyError at /change-part/ 'img_static' any body can help me ? -
Proxy is not reachable from foreign IP's ( Unable to receive SOCKS5 sub-negotiation response )
I just create a new socks5 proxy server ( i use Danete as a server ) in Iran I mean I use the server inside my country and I have an EC2 instance in the us-east-2 region. what I need is to transport some traffic from my AWS EC2 instance to my proxy server in Iran. but now I face some issues the first issue is proxy just work when my request is from ip's in Iran and in this case it works just fine but when I turn on my VPN ( nordvpn USA region ) or make a request from AWS EC2 or any IP from outside of my country I face this error curl: (7) Unable to receive SOCKS5 sub-negotiation response. I have a Django app and need to use this proxy and when i run my Django app in server to user proxy I face this issue requests.exceptions.ProxyError: HTTPSConnectionPool(host='my host', port=443): Max retries exceeded with url: /services/CompositeSmsGateway?wsdl (Caused by ProxyError('Cannot connect to proxy.', RemoteDisconnected('Remote end closed connection without response'))) in my celery worker. I already search the entire internet for a solution but there is no solution for this. This is my dante.conf internal: eth0 port … -
How to update a model inside an exception of a view function and make the transaction commit to the database?
We are trying to create a model to control the number of Access attempts of a user, and then make a call to a function that might throw an exception when, for example, the credentials are not valid. If there is an exception, update the model by incrementing the attempts by one, otherwise update the model in a different way. Everytime we are in the exception branch the model doesn't get created, nor updated. We have tried using s1 = transaction.savepoint() transaction.savepoint_commit(s1) and @transaction.non_atomic_requests but the result gets discarded anyway. There is no way to avoid the exception logic. Django version: Django==2.2.24 access_attempt.py from django.db import models from django.utils.translation import gettext_lazy as _ class AccessAttempt(models.Model): username = models.CharField(_("Username"), max_length=255, null=True, db_index=True) failures_since_start = models.PositiveIntegerField(_("Failed Logins")) validate_jwt_auth.py from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from .models.access_attempt import AccessAttempt from rest_framework import status from rest_framework.exceptions import AuthenticationFailed @transaction.non_atomic_requests def obtain_tokens(request, credentials): attempt = AccessAttempt.objects.filter(username=credentials['username']).first() if attempt is None: attempt = AccessAttempt.objects.create( username=credentials['username'], failures_since_start=0 ) attempt.save() failures = attempt.failures_since_start print(failures) if failures > 5: return {'message': "Failed too many times"}, status.HTTP_403_FORBIDDEN try: with transaction.atomic(): payload = TokenObtainPairSerializer(context={'request':request}).validate(credentials) attempt.failures_since_start=0 attempt.save() return payload, status.HTTP_200_OK except AuthenticationFailed: attempt.failures_since_start += 1 attempt.save() print(attempt.failures_since_start) return {'message': "Unauthorized"}, status.HTTP_401_UNAUTHORIZED views.py def generate_auth(request): … -
Django heroku internal server error after deploying
I have deployed my django app to heroku and I am getting Internal Server Error in the website. settings.py : 'ALLOWED_HOSTS = ['http://127.0.0.1:8000/','https://stripetestdjango.herokuapp.com/', 'localhost'] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] MEDIA_URL = '/images/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) MEDIA_ROOT = BASE_DIR / 'static/images' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' # STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' if os.getcwd() == '/app': DEBUG = False The heroku log shows the below: I have .env file. How to push that to server as well as I am deploying using heroku. I guess the error is it is not able to find my .env file. Please feel free to ask for more details if needed.