Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with textarea "query_utils.DeferredAttribute" message in empty form
I am new in Django and i am making a typical CRUD app. In the "add" section, in the comment textarea this message appears "<django.db.models.query_utils.DeferredAttribute object at 0x03B446A0>" and i dont know what to do. I had tried multiples solutions in other stackoverflow questions but i cant find the solutions, i hope you can help me! Here's the code class Turno(models.Model): date = models.DateTimeField() person = models.ForeignKey('Person', on_delete=models.CASCADE) medic = models.ForeignKey('Medic', on_delete=models.CASCADE) observations = models.CharField(blank=True, max_length=255) def __str__(self): return f'{self.date} {self.person} {self.medic}' def new_turn(request): if request.method == 'POST': turnFormPost = TurnForm(request.POST) if turnFormPost.is_valid(): turnFormPost.save() return redirect("admin_index") turnForm = TurnForm(instance=Turno) context = { 'form':turnForm } return render(request,"turn_new.html", context) class TurnForm(ModelForm): class Meta: model = Turno fields = '__all__' widgets = { 'date': DateTimeInput(attrs={'type':'date'}), 'observations': Textarea(attrs={'rows':5, 'cols':50}) } -turn_new.html <div class="container"> <h2>New Turn</h2> <form method="POST"> {% csrf_token %} <table> {{form}} </table> <button type="submit" class="btn btn-primary">Create</button> </form> <div> <a href="{% url 'new_turn' %}">Back to index</a> </div> </div> in the textarea of 'observations' in 'turn_new.html' the message that appears is this "<django.db.models.query_utils.DeferredAttribute object at 0x03B446A0>" -
Django - Postgres Full Text Search customization word segmentation
I'm trying to implement full-text search functionality for my website. We decided to go for PostgreSQL full-text search on first iterations because of it's simplicity to setup. I found out that Postgres doesn't have good support for our website users' language. Thus the word segmentation came with Postgres will not work. I want to use the tsquery generated by our own parser instead of letting the Postgres function do that for me. Please tell me if there's a way to do it by Django builtin ORM. This is the way Postgres does a full-text search without gin index. SELECT title FROM pgweb WHERE to_tsvector('english', body) @@ to_tsquery('english', 'friend'); If Django ORM cannot achieve the desired functionality, then is it possible to search instead like this by using a custom query and custom parser hosted in my backend? SELECT title FROM pgweb WHERE my_own_parsed_tsvector @@ my_own_parsed_tsquery; Further I'd like to know if building a GIN index with custom parsers are possible. I'd really appreciate it for any possible help. -
Django: Validating POST data from a manually built form
I've built a page that shows a list of all available products (Item) and allows user to add a product to their order, as well as adjust the quantity. My three models: Order Item OrderItem where Item is a model to create products for sale. OrderItem is created once an Item is added to an Order. class Order(models.Model): user = models.ForeignKey(...) class Item(models.Model): title = models.CharField() description = models.TextField() class OrderItem(models.Model): item = models.ForeignKey(Item) quantity = models.IntegerField() order = models.ForeignKey(Order, related_name='items') The page that lists all of the products is essentially a ListView on Item. However, I've annotated the Item.object to include order_item quantity (if it exists): views.py: order_item = request.order.items.filter(item=OuterRef('pk')) items = Item.objects.all().annotate(order_quantity=Subquery(order_item.values('quantity'))) context = { 'items': items } return render(self.request, 'services.html', context) In services.html, I loop through items, and display the title and description, as well as build a form with input box for quantity: <form method="post"> {% for item in items %} {{ item.title }} {{ item.description }} <span onclick="document.querySelector('#item-{{ item.pk }}-quantity').stepDown()" class="minus">—</span> <input style="text-align: center; width: 3rem" class="quantity" min="0" name="{{ item.pk }}" value="{% if item.order_quantity %}{{ item.order_quantity }}{% else %}0{% endif %}" type="number" id="item-{{ item.pk }}-quantity"> <span onclick="document.querySelector('#item-{{ item.pk }}-quantity').stepUp()" class="plus">+</span> </form> Now, in my view, … -
how run celery worker as a part of django management command?
I am totally new with celery + django, so here is the question: I know that according to celery documentation to make it running, we need to create a celery.py file, and then start a worker as an independent process like that: celery -A proj worker -l info I wonder if there is an option to run it through a custom management command instead of running it this way. The reason for this is that I use a third-party django-based platform (oTree), which modifies settings.py before starting, which means that I can't do in celery.py the way they recommend: os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') So if somehow I would manage to start celery from within django (like a custom management command), the environment this process would run in, would already get modified settings, which would work. Any ideas how to do that? -
Iterating through dictionary items from Django html template
I'm new to Django and like to learn the basics first. I was looking for an answer about iterating dictionary from a template. There are couple of questions similar to mine but no one mention the way that is the simplest and works. However, as I don't have enough reputation I can't comment. Therefor, I created this one here as I really want it to be seen. Example: let's say we create our dictionary in the def inside views.py as below: def home_page(request): person = {"name": "Saif", "Phone": 111111111} context = {"person": person.items} return render(request, 'home.html', context) Then in home.html for example, we can iterate easily: {% block body %} {% for key, value in person %} <p>{{ key }}:{{ value }}</p> {% endfor %} {% endblock %} I tried other answers but all didn't work and this one works for me. Thanks, -
Proper auth testing structure in Django
I'm implementing Django REST Framework Social OAuth2 and I'm wondering what my test class / unit tests should look like if I want to imitate 3 out of the 5 testing steps done in the "Testing the Setup" section at: https://github.com/RealmTeam/django-rest-framework-social-oauth2#testing-the-setup I'm basing the structure of my test class on this example: https://docs.djangoproject.com/en/3.1/topics/testing/tools/#example My test.py: import unittest from django.test import Client class SimpleTest(unittest.TestCase): def setUp(self): # Every test needs a client. self.client = Client() self.client_id = <my_client_id> self.client_secret = <my_client_secret> self.user_name = <my_user_name> self.password = <my_password> def test_drf_social_oauth2_setup(self): '''Following testing steps found at https://github.com/RealmTeam/django-rest-framework-social-oauth2#testing-the-setup''' # Retrieve token for user # curl -X POST -d "client_id=<client_id>&client_secret=<client_secret>&grant_type=password&username=<user_name>&password=<password>" http://localhost:8000/auth/token response = self.client.post( '/auth/token', { 'client_id': self.client_id, 'client_secret': self.client_secret, 'grant_type': 'password', 'username': self.user_name, 'password': self.password } ) # Check that the response is 200 OK self.assertEqual(response.status_code, 200) # Check that the response contains an access token self.assertEqual('access_token' in response.json(), True) ;print(f'Token retrieval returned: {response.json()=}') # Refresh token # curl -X POST -d "grant_type=refresh_token&client_id=<client_id>&client_secret=<client_secret>&refresh_token=<your_refresh_token>" http://localhost:8000/auth/token response = self.client.post( '/auth/token', { 'grant_type': 'refresh_token', 'client_id': self.client_id, 'client_secret': self.client_secret, 'refresh_token': response.json()['refresh_token'] # Use refresh token from previous test } ) # Check that the response is 200 OK self.assertEqual(response.status_code, 200) # Check that the response contains a new … -
How to send dictionary context data to view from template in django
I am passing a dict object to template and using that dict object to fill up table data. But depending on the need I want to send that dictionary data to another view for processing. I tried sending data using URL parameter which is affecting data in dictionary. View class GeneratedReportView(View): """ View to display all details about a single patient @param: is_single_document: bool, if true it means only single document exist for patient and to display only one col in html page """ model = Patient template_name = 'patient/patient_generated_report.html' context_object_name = 'object' form = GeneratedReportForm() # helper function def create_final_report(self, doc1_obj: Document, doc2_obj: Document = None, is_single_document: bool = False) : # template of how data is passed on to html page table = { 'doc1_name':'', 'doc2_name':'', 'label':{ 'doc1': {'value':'value', 'unit':'unit'}, 'doc2': {'value':'value', 'unit':'unit'}, 'remark': '', #`doc1_value - doc2_value`, 'remark_color': '', #`red or green`, } } # # some code to populate table data # return table, is_single_document def get(self, request, pk): # instantiating form for selected particular user form = GeneratedReportForm(pk=pk) patient_obj = Patient.objects.get(pk=pk) # retrieving all document of patient.pk = pk from latest to oldest documents = Document.objects.filter(patient__id=pk).order_by('-uploaded_at') table, is_single_document = None, None doc1_obj, doc2_obj = None, … -
Django Rest Framework: How to ignore 'unique' primary key constraint when validating a serializer?
I am attempting to store large amounts of transit data in a PostgreSQL database, where a client uploads multiple records at a time (in the tens of thousands). I only want one arrival time per stop, per route, per trip and the unique identifier for that stop, route, and trip is the primary key for my table (and a foreign key in a different table). I am trying use Django's update_or_create in my serializer to either create the entry for that arrival time or update the arrival time with the latest data if it already exists. Unfortunately, while calling is_valid() on my serializer, it identifies that the repeat records violate the uniqueness constraint of the primary keys (which makes sense), giving me this error message: 'real_id': [ErrorDetail(string='actual with this real id already exists.', code='unique')] I want to override this behavior since if the primary key isn't unique it will just update the entry. I have already tried looping over and removing validators like so: def run_validators(self, value): for validator in self.validators: self.validators.remove(validator) super(ActualSerializer, self).run_validators(value) I have also tried removing all validators using the extra_kwargs field of my serializer Meta class like so: extra_kwargs = { 'name': {'validators': []} } I … -
Error occured when migrate mysql in django
I installed mysql client -- pip install mysqlclient but when i made connection to mysql using this code 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_db', 'USER' : 'root', 'PASSWORD' : '', 'HOST' : '127.0.0.1', 'PORT' : '8080' } following error returns : django.db.utils.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0") -
Templates not found after refactoring settings.py for django-dotenv usage
I want to use django-dotenv to manage my enviroment variables. Before I had 3 files: base.py, dev.py, prod.py. Now I have 1 file: settings.py, that contains everything. However, my templates are not rendering anymore. Why? Every app has a template folder, where the templates are saved. settings.py: import dotenv import sys import os from decouple import config dotenv.read_dotenv() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = os.getenv('SECRET_KEY') DEBUG = os.getenv('DEBUG') from dj_database_url import parse as dburl default_dburl = 'sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3') DATABASES = { 'default': config('DATABASE_URL', default=default_dburl, cast=dburl), } # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # Application definition INSTALLED_APPS = [ 'home', 'search', 'flex', 'streams', 'menus', 'site_settings', 'subscribers', 'blog', 'doctrina', 'storages', 'registration', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.contrib.settings', 'wagtail.contrib.modeladmin', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'django_extensions', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'debug_toolbar', 'crispy_forms' ] SITE_ID = 1 #django-allauth setting MIDDLEWARE = [ 'debug_toolbar.middleware.DebugToolbarMiddleware', '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', 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ## AQUI ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'wagtail.contrib.settings.context_processors.settings', ], }, }, ] AUTHENTICATION_BACKENDS = [ # Needed to login by username … -
password-generator project(identation problem)
hope you are well. I'menter image description here working in this password generator project. And everything was working just fine, till I started adding functions in my views.py document. The error that is showed in the command prompt is an indentation error "unindent does not match any outer indentation level". I attach a screen capture of the issue. Thanks in advance, if someone can help me out!! -
how to fix django instance of a model
Error message AttributeError: 'NoneType' object has no attribute 'add' am trying to create an instance of a model. the card model is suppose to be an instance of the patient model and the patient model has a foreign key relations with the user model. Its like a patient who has a card in the hospital. My error is coming from the perform_create method views.py class PatientCardListAPIView(ListCreateAPIView): serializer_class = PatientsCardSerializer queryset = Card.objects.all() permission_classes = (permissions.IsAuthenticated, IsOwner, ) def perform_create(self, serializer): serializer.save() serializer.instance.owner.add(self.request.user) models.py from django.db import models from authentication.models import User # Create your models here. class Patient(models.Model): name = models.CharField(max_length=255, null=True) country = models.CharField(max_length=255, null=True) state = models.CharField(max_length=255, null=True) phone = models.CharField(max_length=255, null=True) email = models.CharField(max_length=255, null=True) owner = models.ForeignKey(to=User, null=True, on_delete=models.CASCADE) def __str__(self): return self.name class Card(models.Model): name = models.CharField(max_length=255, null=True) card_number = models.CharField(max_length=255, null=True) owner = models.OneToOneField(Patient, null=True, blank=True, on_delete=models.CASCADE) def __str__(self): return self.name -
combine multiple swagger docs ( from different applications ) into one swagger dashboard [drf_yasg]
If I have 5 applications(django),with respective swagger docs, is it possible to combine all the swagger docs as one swagger docs. I'm using django rest framework. -
Django- Admin Section Improper View
I am Using Django 3 and I'm facing a weird issue in admin section. The Home page of Admin section looks proper: Admin Home But when I click on one of the tabs, the page has a random navigation bar which does not gets closed. It blocks all of the view of the page. Messed up View I haven't altered the CSS of Admin section or anything. Still I'm getting this error. How can this be solved? I can't work on admin section properly because of this. -
Django Template not rendering mission information
I'm trying to render some information in the template but it isn't showing on even though I think I implemented it right. I'm working on my consultant dashboard (consultant is a user type) My template : <div class="form-group"> {% csrf_token %} <label>Mission </label> <select class="form-control" name="mission" id="mission"> {% for mission in mission %} <option value="{{ mission.id }}">{{ mission.mission_name }}</option> {% endfor %} </select> </div> models.py: class Mission(models.Model): id=models.AutoField(primary_key=True) mission_name=models.CharField(max_length=255) client_id=models.ForeignKey(Client,on_delete=models.CASCADE,default=1) consultant_id=models.ForeignKey(Consultant,on_delete=models.CASCADE) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() My view: def staff_take_attendance(request): mission=Mission.objects.filter(consultant_id=request.user.id) return render(request,"staff_template/staff_take_attendance.html",{"mission":mission}) -
Django celery unable to set custom scheduler as DatabaseScheduler
I have a Django project setup and working. Celery is also working i am able to start worker as well as celery beat. Trying to use django_celery_beat and set custom scheduler class as django_celery_beat.schedulers:DatabaseScheduler in the settings file. But its still using the default PersistentScheduler. settings.py # Other settings # Celery CELERY_BROKER_URL = 'redis://localhost:6379/0' CELERY_CELERYBEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler" CELERY_RESULT_BACKEND = 'django-db' celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from celery.schedules import crontab # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() # my tasks imported here However when i set custom scheduler in command line like this celery -A proj beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler then everything works as expected. In nutshell, i want to set celery's custom scheduler in the django settings.py so that i don't need to specify that everything in the command line. UPDATE: If i change broker_url in the settings, the changes as reflected well. So there's nothing wrong with configuring settings. -
Different url path than pk in Django Generic View
I am using DetailView to display a template with the information about my object from my model. I used int:pk as the path for my object, but now I want to access the view from something like detail/XX-ABC (where XX-ABC stands for a unique field from my model). I didn't find a way to pass this slug and display the object. path(r'detail/<int:pk>/', views.DetailClientsView.as_view(template_name='clients/clients_details.html', context_object_name='client'),name='details_client'), And this is my View. class DetailClientsView(DetailView, UpdateView): model = Clients form_class = InspectionForm def get_success_url(self): return reverse('search:search') -
How to block/override djoser user/me endpoint?
I would like to know if there is a chance to block the djoser's user/me endpoint for specific request methods. I don't see this in the docs. Problem: Now when I have two users { email: 'a@exa.com' }, and { email: 'b@exa.com' }. I can use the first user to change his email to match the 2nd user's email, so both will have the same email, and the second one will be blocked cos of that. Is there an elegant way to check if the email exists from the djoser's level? -
Configure Highcharts JS within Django template
I am working with HighCharts for the first time in Django and ran into two issues. It's a column chart which groups transactions per month, but the months on the X-axis is being named to 0, 1, 2 etc instead of Jan, Feb, Mar. The second issue originates from a solution I tried for issue number one, I tried to manually add xAxis to my JS script located in the template file as below, but this breaks my chart. So how do I modify the Highchart JS properly? For example I have added StyleMode: True in my views.py file, but it doesn't seem like I can modify the chart when it comes to the months for the X-axis in that way. <script> Highcharts.chart('container', { xAxis: { categories: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep' ] } {{ chart|safe }}}); </script> My template which contains my highcharts JS <script src="https://code.highcharts.com/highcharts.src.js"></script> <script> Highcharts.chart('container', {{ chart|safe }}); </script> My views.py # Bar chart - Transactions per month month = [] total_entries = [] for entry in transactions_per_month: month.append('%s Class' % entry['month']) total_entries.append(entry['total_entries']) total_entries = { 'name': 'Month', 'data': total_entries, 'color': 'green' } chart = { 'chart': {'type': 'column', 'styleMode':'true'}, 'title': … -
Get content from meta in external website
I need to extract the meta description of an external website. I've already searched and maybe the simple answer is already out there, but I wasn't able to apply it to my code. Currently, I can get its title doing the following: from urllib.request import urlopen from lxml.html import parse url = "https://technofall.com/how-to-report-traffic-violation-pay-vehicle-fines-e-challan/" page = urlopen(URL) p = parse(page) print (p.find(".//title").text) I am getting title from here However, the description is a bit trickier. It can come in the form of: <meta name="og:description" content="blabla" <meta property="og:description" content="blabla" <meta name="description" content="blabla" So what I want is to extract the first one of these that appears inside the Html. -
Whole page refreshing after AJAX success in Django
I am new to Django and trying to use AJAX for entering and showing a data form a simple form. Here is the html code for form. Task.html <!DOCTYPE html> {% load static %} <script lang="en"></script> <head> <meta charset="UTF-8"> <title>Task</title> </head> <body> <div id="div_yo"> <form method="post" id="form_1"> {% csrf_token %} {{ form }} <button type="submit" name="Submit" class="btn yoyo">Submit</button> </form> {% for items in item %} <h4 class="heading">{{ items.id }} . {{ items }}</h4> <br> {% endfor %} </div> </body> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {% block scripts %} <script src="{% static 'home.js' %}"></script> {% endblock %} </html> Javascript file **home.js** console.log("i am working here"); //$(document).on('submit','#btn' ,function(e){ $('#form_1').submit(function (e){ //e.preventDefault(); var form_data = document.getElementById('form_1').value; console.log(form_data); //alert("Working"); $.ajax('', { type: 'POST', data: { item: form_data, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val() }, success: alert("added to backend"), } ) }); Python file views.py from django.shortcuts import render, redirect from . import models from .models import * from .forms import * from django.http import HttpResponse # Create your views here. def homepage(request): form = to_do_form() if request.method == 'POST': form = to_do_form(request.POST) if form.is_valid(): form.save() return redirect('homepage') else: form = to_do_form() item = to_do_task.objects.all() mess = "success" context = {'form': form, 'item': item, 'mess': mess} return render(request, 'task.html', context) The problem here … -
Django - Cannot query "email@wp.pl" : Must be "User" instance
Im working on simple registration and login application in Django, but unfortunately when im trying to send request via Postman, its respond with 500 Code and long error at the end with Cannot query "email@wp.pl" : Must be "User" instance.. Here is my models.py from Account without headers: class MyAccountManager(BaseUserManager): def create_user(self,email,username,password = None): if not email: raise ValueError("User must have email") if not username: raise ValueError("User must have name") user = self.model( email = self.normalize_email(email), username = username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,username,password): user = self.model.objects.create( email = self.normalize_email(email), password = password, username = username, ) Token.objects.create(user=instance) user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(max_length=60, verbose_name="email",unique=True) username = models.CharField(max_length=30, unique=True) REQUIRED_FIELDS = ['username',] def __str__(self): return self.email @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender,instance=None,created=False,**kwags): if created: Token.objects.create(user=instance) -
Django email Mailbox cannot be accessed
I have the following configuration for sending email EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = 'myemail@mydomain.com' EMAIL_HOST_PASSWORD = '**********' from Django shell I send the mail like this >>> from django.core.mail import send_mail >>> send_mail('Test','test message','myemail@mydomain.com',['destinationaccount@gmail.com'],fail_silently=False) but i get the following error smtplib.SMTPAuthenticationError: (550, b'5.2.1 Mailbox cannot be accessed [BN1PR12CA0001.namprd12.prod.outlook.com]') -
How do I model tables from an existing database if they belog to different schemas in python models.py (Django)?
Fox example , I have 3 tables users, sales both from sales_deparment schema, and I have another one called invoices in a schema payments in a database called sample_enterprise. How do I map these there tables with the models.py -
Heroku Django: ValueError: Missing staticfiles manifest entry
Hi I am getting an Internal server error when I run my website and I get the above error: raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) 2020-09-07T16:55:13.210685+00:00 app[web.1]: ValueError: Missing staticfiles manifest entry for 'css/main.css' Now my project is called register and the file tree is: --register ----register ------wsgi.py ------settings ----------common.py ----------production.py ----------development.py ----static ----manage.py In my production.py file I have: STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' db_from_env = dj_database_url.config(conn_max_age=600) DATABASES['default'].update(db_from_env) STATIC_ROOT = os.path.join(BASE_DIR, 'static') and in my common.py file I have: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') #STATIC_DIR = os.path.join(BASE_DIR,'static/') MEDIA_DIRS = [ os.path.join(BASE_DIR,'media') ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' STATIC_URL = '/static/' I tried running python manage.py collectstatic however I get the following error: No such file or directory: '/Users/apple/Documents/Project/main/register/register/static' How can I resolve this issue as in development settings it seems to run correctly but in production it gives me a server 500 error. EDIT According to WhiteNoise documentation: I have set: WHITENOISE_USE_FINDERS=True In my commony.py file however, now I am getting an error: for entry in os.scandir(path): 2020-09-07T17:11:40.454766+00:00 app[web.1]: FileNotFoundError: [Errno 2] No such file or directory: '/app/register/static' :