Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Send a field from ListAPIView to Serializer in Django Rest Framework
I'm building a leaderboard view for a REST API I'm designing in DRF. I need a bit of help in reducing an inefficiency. views.py class LeaderboardAPIView(ListAPIView): serializer_class = UserSerializerLeaderboard permission_classes = (IsAuthenticated,) def get_queryset(self): queryset = User.objects.all() queryset = list(queryset) queryset.sort(key=operator.attrgetter("total_karma"), reverse=True) queryset = queryset[:10] return queryset serializers.py class UserSerializerLeaderboard(serializers.ModelSerializer): score = serializers.SerializerMethodField(read_only=True) place = serializers.SerializerMethodField(read_only=True) def get_score(self, obj): return obj.total_karma def get_place(self, obj): return "1" class Meta: model = User fields = ("score", "place") The get_place method currently returns a placeholder of 1. I'd like it to return the actual place the user is in, sorted by score. Now, I know I'm already calculating this in the queryset, so I don't want to repeat this inefficiently. How can I send the place of the user to the serializer directly, rather than repeating the calculation in the method? -
How to generate a list of request.POST in Django
I have the following code in views.py: def valores(request): global peso_unitario, preco_unitario peso_unitario=[] preco_unitario=[] N=a print('N='+str(N)) for i in range(N): peso_u = request.POST['peso_u'] preco_u = request.POST['preco_u'] if peso_u.isdigit() and preco_u.isdigit(): c = int(peso_u) d = int(preco_u) peso_unitario.append(c) preco_unitario.append(d) print(a) if i==N-1: return render(request, 'pacote.html', {'peso_unitario': peso_unitario, 'preco_unitario': preco_unitario}) else: res = 'Apenas numero.' return render(request, 'pacote.html', {'res': res}) One step before, where we filled a text field with a number N. Now, I'd like to generate N text fields to be filled by the user, but I don't know how to do this. -
I want to create contact form with some validation in Django views.py file
I want to validation that if user fill contact form with number and again try with same number it will not allow to fill form till some days after they can fill form again with same number in Django. -
Python: 'NoneType' object is not subscriptable
Asking for some help on this one. def home(request): client = pymongo.MongoClient(settings.MONGO_SERVER) main_db = client[settings.MONGO_DATABASE] get_main_config = main_db.configurations.find_one({"name": "main_config"}) return render(request, 'dashboard/home.html', {"data": get_main_config["homepage_urls"]}) Traceback (most recent call last): render(request, 'dashboard/home.html', {"data": get_main_config["homepage_urls"]}) TypeError: 'NoneType' object is not subscriptable Why the error occured on that line? Thank you. -
Django session timeout handler
I have a function my_logout_handler() that needs to be called when a user logs out. I am calling the function in the logout function as below. def logout(request, login_url=None, **kwargs): // original code here my_logout_handler() It works perfect except that it is not called when user is logged out due to session timeout. Where should I put my code for it to get called on session timeout? -
django.core.exceptions.improperlyconfigured unknown parameters loader
Good day everyone! I'm tryna create affiliate marketing website, but have been having some errors lately this the kind of error i got when i run python manage.py runserver django.core.exceptions.improperlyconfigured unknown parameters loader -
Calculate the ForeignKey type Percentage (individual) Django ORM
I want to calculate the percentage of all car types using Django ORM, or group by all of the cars on the basis of their types, and calculate the percentage. I've multiple solutions but they are old-fashioned and itrative. I am going to use this query over the dashboard where already multiple queries calculating different analytics. I don't want to compromise on performance, that's why I prefer the single query. Here is the structure of my tables (written) on Django: class CarType: name = models.CharField(max_length=50) class Car: car_type = models.ForeignKey(CarType, on_delete=models.CASCADE) I have a utility function that has the following details: input => cars: (Queryset) of cars Django. output => list of all car_types (dictionaries) having percentage. [{'car_type': 'car01', 'percentage': 70, 'this_car_type_count': 20}, ...] What I've tried so far: cars.annotate( total=Count('pk') ).annotate( car_type_name=F('car_type__name') ).values( 'car_type_name' ).annotate( car_type_count=Count('car_type_name'), percentage=Cast(F('car_type_count') * 100.0 / F('total'), FloatField()), ) But, this solution is giving 100% on all car_types. I know this weird behavior is because of the values() I'm using, but I've kinda stuck it here. -
Unable to install this app without the developer's account , zoom OAuth2
Unable to install this app without the developer's account. Please contact the app developer to install. Edit on Web Portalenter image description here -
Create pages programaticallhy with Django and Wagtail
I managed to programatically create pages using Django Management Commands as shown here and here. How do I link those pages to other models like tags, categories and authors? Here is the model of the page I want to create: class BlogPage(Page): ## Fields I can create programatically date = models.DateField("Post date") intro = models.CharField(max_length=250) body = RichTextField(blank=True) ## Fields I dont know what to do with tags = ClusterTaggableManager(through='BlogPageTag', blank=True) categories = ParentalManyToManyField('blog.BlogCategory', blank=True) authors = ParentalManyToManyField('blog.BlogAuthor', blank=True) def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None -
Django - How to render a ModelForm with a Select field, specifying a disabled option?
I have the following models: # Get or create a 'Not selected' category def get_placeholder_categoy(): category, _ = ListingCategories.objects.get_or_create(category='Not selected') return category # Get default's category ID def get_placeholder_category_id(): return get_placeholder_categoy().id class ListingCategories(models.Model): category = models.CharField(max_length=128, unique=True) def __str__(self): return f'{self.category}' class Listing(models.Model): title = models.CharField(max_length=256) seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name='listings') description = models.TextField(max_length=5120, blank=True) img_url = models.URLField(default='https://media.istockphoto.com/vectors/no-image-available-picture-coming-soon-missing-photo-image-vector-id1379257950?b=1&k=20&m=1379257950&s=170667a&w=0&h=RyBlzT5Jt2U87CNkopCku3Use3c_3bsKS3yj6InGx1I=') category = models.ForeignKey(ListingCategories, on_delete=models.CASCADE, default=get_placeholder_category_id, related_name='listings') creation_date = models.DateTimeField() base_price = models.DecimalField(max_digits=10, decimal_places=2, validators=[ MinValueValidator(0.01), MaxValueValidator(99999999.99) ]) With these, I have the following form: class ListingForm(ModelForm): class Meta: model = Listing exclude = ['seller', 'creation_date'] widgets = { 'title': TextInput(attrs=base_html_classes), 'description': Textarea(attrs=base_html_classes), 'img_url': URLInput(attrs=base_html_classes), 'category': Select(attrs=base_html_classes), 'base_price': NumberInput(attrs=base_html_classes) } One of the available categories I have is "Not selected", since I want to allow that if at some point a category were to be removed, items can be reassigned to that one, however, when rendering the form, I will do some validation on the view function to prevent it from being submitted if the "not selected" category is sent with the form. Because of this, I want the HTML form on the template to assign the 'disabled' attribute to the option corresponding to that category, however, I have been searching for a … -
Django: Admin site not assigning permission group to user
I am trying to add a user to an existing permission group using the Django admin site. The problem is, when I add the group to the user using the admin drop-down, the group is not assigned despite the UI showing that it is. I can see the user has not actually been added to the group in the Django shell >>> from api.models import User >>> user = User.objects.get(id=1) >>> user.groups.all() <QuerySet []> When I used the shell insead of the admin site to add the group to the user it works however >>> from api.models import User >>> from django.contrib.auth.models import Group >>> group = Group.objects.get(name='System admin') >>> user = User.objects.get(id=1) >>> user.groups.add(group) >>> user.groups.all() <QuerySet [<Group: System admin>]> It is becoming tedious to edit permission groups for users using the shell. What are some reasons why the admin site is not properly assigning groups to users? -
How to pass the value from a function in Django
In views.py I have the following code: def basic(request): n_objetos=request.POST['n_objetos'] peso_maximo=request.POST['peso_maximo'] if n_objetos.isdigit() and peso_maximo.isdigit(): a=int(n_objetos) b=int(peso_maximo) print(a) return render(request, 'valores.html', {'n_objetos': a, 'peso_maximo': b}) else: res='Apenas numero.' return render(request, 'valores.html', {'res': res}) Here everything is great, but the next step is being the problem. In the next step I want to use both integer values a and b, they were returned in render {'n_objetos': a, 'peso_maximo': b}, but I don't know how to do this. I need to use them in other functions but I have no ideia how to do this. -
How can I fetch variables sent by django with javascript?
{% extends 'base.html' %} {%load static%} <link rel="stylesheet" href="{% static 'css\common_movie_tv.css' %}"> {% block content %} <table> <tr> <tr> <th>name</th> <th>created_at</th> <th>comment</th> <th>evaluation</th> </tr> {% for c in object_list %} <tr> {{ c.tv.id|json_script:"tv_id" }} <div></div> <td>{{ c.user.nickname }}</td> <td>{{ c.created_at }} </td> <td>{{ c.comment }}</td> <td><h2 class = "rate" style="--rating:{{c.stars}}">{{c.stars}}</h2></td> </tr> {% endfor %} </table> <script> const TMDB_API_KEY = "xxxxxxxxxxx"; const tv_id = JSON.parse(document.getElementById('tv_id').textContent); fetch(`https://api.themoviedb.org/3/tv/${tv_id}?api_key=${TMDB_API_KEY}&language=en-US`, { method: "GET", headers: { "Content-Type": "application/json" }} ) .then(res => res.json()) .then(data => { console.log(data) })</script> {% endblock %} I want to send comment_tv.tv.id in this code to javascript. I want to change tv_id to comment_tv.tv.id. How I do change the code? I want to display TV images between divs, but I can't display them even if I do console.log and I don't know if I can fetch them. What should i do? -
AttributeError: object has no attribute 'pk'
I am trying to insert some data into MySQL database (model LogsSeparate) through Django and Django Rest Framework but I keep getting an error which I bet is very easy to solve yet I couldn't figure it out myself: Error: if obj.pk is None: AttributeError: 'LogObjTest' object has no attribute 'pk' Code: class LogObjTest(): def __init__(self): self._id = None self.bits = None class getLogs(viewsets.ModelViewSet): arrayTest=[] for x in Logs.objects.all(): serializer_class = LogsSeparateSerializer test = Fields.objects.filter(pac_id=x.message_id_decimal) binaryTest=x.data_binary for i in test: obj=LogObjTest() obj._id=x.message_id_decimal obj.bits=binaryTest[i.fld_offset:i.fld_offset+i.fld_len] arrayTest.append(obj) queryset = arrayTest LogsSeparate.objects.bulk_create(arrayTest) print("arrayTest",arrayTest)``` -
Django rest - make serializer for create object by both child and parent class datafields
User object and Teacher object are creating but "name" field of Teacher object is not getting the data. postman POST: { "email":"b@gmail.com", "password":"b1234", "password2":"b1234", "Teacher":{"name":"b"} } serializers- view.py class TeacherSignupView(generics.GenericAPIView): serializer_class=UserSerializer def post(self, request, *args, **kwargs): serializer=self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user=serializer.save() return Response({ "user":UserSerializer(user, context=self.get_serializer_context()).data, "token": Token.objects.get(user=user).key, "message":"account created successfully" }) serializers- serializers.py class TeacherSignupSerializer(serializers.ModelSerializer): class Meta: model=Teacher fields=['name'] user=Teacher class UserSerializer(serializers.ModelSerializer): Teacher=TeacherSignupSerializer() password2=serializers.CharField(style={"input_type":"password"}, write_only=True) class Meta: model=User fields=['email','password', 'password2', 'Teacher'] extra_kwargs={ 'password':{'write_only':True} } def create(self, validated_data): t_data=validated_data.pop('Teacher') user=User( email=self.validated_data['email'] ) password=self.validated_data['password'] password2=self.validated_data['password2'] if password != password2: raise serializers.ValidationError({"error":"Password did not match"}) user.set_password(password) user.is_teacher=True user.save() for name in t_data: Teacher.objects.create(user=user, name=name) return user -
Why is model's clean run when viewing an already submitted form?
I have a website that allows users to submit the same form several times (but with different input) but also allows them to view each form they submitted and edit it. The problem is with the "key_name" field. If I view an already submitted form (edit_keydef) then there is the ValidationError message with the field highlighted in red, when in fact my intention is for that ValidationError to occur only when they are about to submit but have provided the same name as another form. (The view used when filling in the form is different to that when editing the form - as with the editing there's more fields) but both views use the same model. I don't understand why DJango runs the clean() function when the form has already been sumbitted, i.e. the validation has already occurred and the data has already been submitted views.py def edit_keydef(request, id): data = {'title': 'View or Edit Key Definition'} template = 'generate_keys/edit_keydef.html' keydef = get_object_or_404(KeyDefinition, pk=id) if request.method == "POST": keydetails_form_instance = KeyDefDetailsForm(request.POST, instance=keydef) if 'Save' in request.POST: if keydetails_form_instance.is_valid(): if keydetails_form_instance.cleaned_data['encoded_activation_key']: activation_obj = Activation() result = activation_obj.GenerateKey(keydef) keydetails_form_instance.save() return redirect('/key/edit/' + str(id)) else: log.debug(keydetails_form_instance.errors) if 'Generate' in request.POST: if keydetails_form_instance.is_valid(): activation_obj … -
How to access the detail object when writing to a nested serializer on a ModelViewSet action?
I'm having trouble using actions to populate a nested serializer. I have a parent model called Allocation, and a child model, Trade (one-to-many). I have a ModelViewset for Allocation, and I want it to have an action method that allows me to post the JSON containing a list of Trades, and create them with the relation to the parent model populated. How do I access the parent's object or PK on my TradeSerializer so I can populate it's PrimaryKeyRelatedField? class AllocationViewSet(ModelViewSet): serializer_class = AllocationSerializer queryset = Allocation.trades.all() lookup_field = "reference_date" # The detail=True makes the url allocation/2022-07-25/import_pre_allocation/ # The 2022-07-25 uniquely identifies my allocation instance. @action(detail=True, methods=['POST']) def import_pre_allocation(self, request, reference_date=None): allocation_obj = self.get_object() # here I`m trying to pass my parent object as a context element serializer = TradeSerializer(data=request.data, many=True, context={'allocation_pk': allocation_obj.pk}) if serializer.is_valid(): for trade in serializer.validated_data: trade["allocation"] = allocation_obj print(serializer.data) return Response(serializer.data) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class TradeSerializer(serializers.ModelSerializer): quantity = serializers.DecimalField(required=False, max_digits=Trade.TRADE_QUANTITY_MAX_DIGITS, decimal_places=Trade.TRADE_QUANTITY_DECIMAL_PLACES) allocation = serializers.PrimaryKeyRelatedField(write_only=True, required=False,queryset=Allocation.objects.all()) def perform_create(self, serializer): # How do I populate my allocation field with the allocation_obj received from context? allocation_obj = Allocation.objects.get(pk=self.request.allocation_pk) serializer.save(allocation=allocation_obj) class Meta: model = Trade fields = ["allocation","quantity"] -
Django. modal window ModelForm posts to the page from which it is opened
My Django project has an app with class-based views and forms. Some forms are rendered in a modal window via js script. The script renders the forms in modal form but submitting is performed by Django ModalForm. It is suitable for me. Examples of form, js, and template are below. main.js function initSampleForm(form, modal) { /*initDateFields();*/ form.find('input[name="cancel_button"]').click(function(event){ modal.modal('hide'); return false; }); form.ajaxForm({ 'dataType': 'html', 'error': function(){ alert('Помилка на сервері'); return false; }, 'success': function (data, status, xhr) { var html = $(data), newform = html.find('form').attr('id', 'content-column'); modal.find('.modal-body').html(html.find('.alert')); if (newform.length > 1) { modal.find('.modal-body').append(newform); initSampleForm(newform, modal); } else { modal.find('.modal-body').append(newform); initSampleForm(newform, modal); setTimeout(function(){location.reload(true);}, 500); } } }); } function initAddSamplePage() { $('a#addSampleBtn').click(function(event){ event.preventDefault(); var link = $(this); $.ajax({ 'url': link.attr('href'), 'dataType': 'html', 'type': 'get', 'success': function(data, status, xhr){ if (status != 'success') { alert('Помилка на сервері'); return false; } /*else { html2 = $(data) alert(html2.find('form').attr('id', 'content-column').text()); }*/ var modal = $('#LgModal'); html = $(data), form = html.find('form').attr('id', 'content-column'); modal.find('.modal-title').html(html.find('#Title').text()); modal.find('.modal-body').html(form); initSampleForm(form, modal); modal.modal('show'); $('.modal').on('shown.bs.modal', function () { $('select').select2({ theme: 'bootstrap4', }); }); }, 'error': function(xhr, status, error){ alert('Помилка на сервері'); return false; } }); return false; }); } forms.py class SampleForm(ModelForm): class Meta: model = Sample fields = ['sample_name', 'sample_normative', 'sample_date', … -
Fix SSLError in django request to external API
So I have a couple sites made with django and never seen this type of error before. this site presents data from a API, so I hooked the API up with try: r = requests.post(url, data=json.dumps(dados), headers=headers, timeout=30) except Timeout: raise EmptyResultSet(f'Erro API TIMEOUT') if r.status_code == requests.codes.ok: search = r.json() else: search = [] So, I hook he request with the API server, and check for a timeout so django sends me an e-mail about that (with the EmptyResultSet because the site can't display properly when no data is received) then, if the code is ok it gets the data, and if there is an error it sets search = [] which gets data from a cache later in the code this snippet was working normally, but then my production server started receiving this error: HTTPSConnectionPool(host='****', port=443): Max retries exceeded with url: /api/Site/Busca (Caused by SSLError(SSLError('No cipher can be selected.'))) host hidden for safety So, in local machines the site runs just fine and the people behind the API said my server isn't blacklisted this time, so I don't know where to search for some solution. Django version is 3.2.14, requests is 2.28.1 and urllib3 is 1.26.11 -
Fix MySQL Django error "Access denied for user" without elevating user's privileges
I am migrating to a cloud managed MySQL database, which has more restricted users. When I switch my Django connection string to this new database, I get the error "(1045, Access denied for user 'db_user'@'X.X.X.X (using password: YES)")" while doing a simple select from the Django ORM. This user already has schema change access even though this app is almost 100% read only. When the Django application was created, it was intended to allow migrations with a code-first approach; however we've diverged from that to a database-first approach. So migrations are no longer necessary. How do I fix this error without granting all privileges, like many of the other solutions here suggest? All the db models in the code already have managed=false set. -
Apscheduler cronjob loop does some but not all entries multiple times
Hy all i had a question concerning apscheduler and a forloop So here is my job which takes all the entries from a database and checks them with the current hour if there is no valid entry already, save one to the db: from datetime import datetime from website.models import * from website.forms import * import website.lib.definer as dfin import website.lib.formsaver as frmsave all_in_use_items = PersonalisedItemInfo.objects def pitemjob(): for items in all_in_use_items: last_itemdatabase_entry = PersonalisedItem.objects.filter(item_info=items).order_by('-creation_date')[0] last_entry = last_itemdatabase_entry.creation_date last_entry_formatted = last_entry.strftime("%y-%m-%d %H") now = datetime.now() current_time = now.strftime("%y-%m-%d %H") if last_entry_formatted == current_time: pass else: ptif_form= PersonalisedItemInfoForm(instance=items) url = ptif_form.instance.url price = dfin.ptdefiner(url) PersonalisedItem.objects.create( item_info = items, price = price ) In my scheduler.py file i have: def start(): scheduler = BackgroundScheduler(timezone="Europe/Berlin") scheduler.start() scheduler.add_job(pitemjob,'cron', hour='20') Now everything works fine if i don't use this forloop the output is nice and in order but not accounted for. So sometimes I have double entries considering what the users inputted. That is exactly what i want to avoid with my forloop. normal output: Database item entry 1 Database item entry 2 Database item entry 3 Database item entry 4 but my forloop output gives something like this: Database item entry 3 Database item … -
celery re-running the same tasks over and over again indefinitely if there are any issues with rabimq/celery server in Python
I have searched about this but did not get an expected answer. There is the same question asked but it applies to raids which can be solved by setting, BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600*10} # 10 hours I tried this but does not work as I got to know that this applies only to Redis and for rabitmq we have to use consumer_timeout. But not sure how can we set it up? or how to use it with rabitmq python/Django setting. I am using amqp==2.6.1, celery==4.2.2, Python 3.8 Django==3.0.4. and CELERY_BROKER_TRANSPORT configurations, CELERY_BROKER_TRANSPORT_OPTIONS = { 'max_retries': 3, 'interval_start': 0, 'interval_step': 0.5, 'interval_max': 3, } Running multiple celery shared_task at a time. In the middle, if the rabbitmq is down or any issues with the server. I can see celery re-running the same tasks over and over again indefinitely. How to stop this re-running the celery task indefinitely? -
{'user': ['This field is required.']} in django while making a post request from a python client
I am trying to register a reader (extended django User model) making a post request from python client. I have provided the user data while making a post request from a python client to 'reader-register'. Still I am getting this error: {'user': ['This field is required.']}. But it works fine from browsable API of django rest framework. Here are the relevant codes. class ReaderSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) class Meta: model = Reader fields = ['user', 'photo_url', 'bio'] def create(self, validated_data): print(self.initial_data) user_data = validated_data.pop('user') user = User.objects.create(**user_data) reader = Reader.objects.create(user=user, **validated_data) return reader def update(self, instance, validated_data): user_data = validated_data.pop('user') user = instance.user user.username = user_data.get('username', user.username) user.email = user_data.get('email', user.email) user.first_name = user_data.get('first_name', user.first_name) user.last_name = user_data.get('last_name', user.last_name) user.save() instance.photo_url = validated_data.get( 'photo_url', instance.photo_url) instance.bio = validated_data.get('bio', instance.bio) instance.save() return instance UserSerializer class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) class Meta: model = User fields = ['username', 'password', 'email', 'first_name', 'last_name'] extra_kwargs = { 'password': { 'write_only': True, 'required': True, }, 'first_name': { 'required': True, }, 'last_name': { 'required': True, }, 'username': { 'required': True, }, } APIView class ReaderRegisterAPIView(CreateAPIView): serializer_class = ReaderSerializer permission_classes = [AllowAny] python client import requests data = { "user": { "username": "a", "email": … -
CRISPY_TEMPLATE_PACK doesn't work with pyinstaller
Hi I have a djnago app which is using websockets and django channels. I have converted it in an exe file with pyinstaller. Everything is working fine just my signup page is not working. I have used crispy_forms in it. When I run my exe file and open signup url, it gives me this error below is my spec file I know that I have to add CRISPY_TEMPLATE_PACK = "bootstrap4" somewhere but I dont know where should I add it -
ValueError: Missing staticfiles manifest entry for 'css/theme-style.css' Deploy in Heroku
I have a Django system that already works on Heroku and recently I needed to do some updates on this system, it turns out that now, when I try to upload it again to Heroku I'm getting an error in this deploy. Apparently Heroku can't report that it can't find the file "css/theme-style.css" When facing this problem, I made a clone of the system that is currently working and I tried to upload it again changing only a commented line "#hello" inserted in the views, when deploying the system "no changes" other than "#hello" and the same error is being presented (which leads me to believe that the problem is not in my updates). These are my file settings: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'accounts', 'core', 'users', 'widget_tweaks', 'whitenoise.runserver_nostatic', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', 'whitenoise.middleware.WhiteNoiseMiddleware', "core.error_handler.ErrorHandlerMiddleware", ] STATIC_URL = '/static/' STATIC_ROOT = '/core/static/' #looks weird, but it's located in this folder STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' When I try to run with 'heroku local' the same error is displayed. Have you ever had this situation when deploying to Heroku?