Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UpdateView post() returns success message even if user tries to submit disabled form field
I've made a custom django form and mark email field as disabled. If someone tries to remove readonly attribute from browser's developer console and submits the form, email isn't updated but it doesn't show error message either it just shows success_message I've in my Update view. Is there any way to handle this and return error message instead of success. Below are the code snippets class ProfileView(AdminRequiredMixin, SuccessMessageMixin, UpdateView): template_name = '/profile.html' form_class = UpdateProfileForm success_message = 'Profile Updated Successfully' and the UpdateProfileForm class UpdateProfileForm(forms.ModelForm): email = forms.CharField(disabled=True) class Meta: model = User fields = ['image', 'name', 'role', 'email'] Now i want if user tries to submit the email forcefully, it shows an error message that email isn't editable or so. -
LookupError: App 'app' doesn't have a 'CustomUser' model
So I added the following line in my settings.py: AUTH_USER_MODEL = 'app.CustomUser' And I got the error: LookupError: App 'app' doesn't have a 'CustomUser' model. The last line in error is: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'app.CustomUser' that has not been installed Here is my CustomerUser class in app/models.py: from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser from django.utils import timezone class CustomUser(AbstractUser): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='CustomUser') name = models.CharField(max_length=500) phone = models.CharField(max_length=30) email = models.CharField(max_length=500) class Meta: abstract = True I get this error while trying to run makemigrations. I already have an existing db, and I'm redoing my models. I tried deleting the database file, and no luck. -
How can I update the object and create one at specific time with Django?
I am building an auction website, and I need to create an Object that shows us the winner of the auction once the auction has been ended! my models.py class Auction(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) start_time = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) end_time = models.DateTimeField() #when times up Winner should be created Automatically start_price = models.DecimalField(verbose_name="Original Price", max_digits=15, decimal_places=1, default=0.0) current_price = models.DecimalField(verbose_name="Current Price", max_digits=15, decimal_places=1, default=0.0) next_price = models.DecimalField(verbose_name="Next Price", max_digits=15, decimal_places=1, default=0.0) step = models.DecimalField(verbose_name="Raise Price", max_digits=15, decimal_places=1, default=0.0) sold_price = models.DecimalField(verbose_name="Sold Price", max_digits=15, decimal_places=1, blank=True, null=True) is_active = models.BooleanField(default=True) is_manual = models.BooleanField(default=True) def __str__(self): return self.product.title class Bid(models.Model): Types = ( ('auto', 'Automatically'), ('user', 'By user own') ) auction = models.ForeignKey(Auction, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) time = models.DateTimeField(auto_now_add=True) price = models.DecimalField(verbose_name="Bid Price", max_digits=15, decimal_places=1, default=0.0) action = models.CharField(max_length=120, default="user", choices=Types) def __str__(self): return str(self.price) class Winner(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) auction = models.ForeignKey(Auction, on_delete=models.CASCADE) won_price = models.DecimalField(verbose_name="Won Price", max_digits=15, decimal_places=1) won_time = models.DateTimeField() def __str__(self): return self.user.username For the auction process, I am using Django Channels which means I can create the winner if the auction page has viewers(when WebSocket is on) else I am not able to do that! Thats why I have to do it … -
creating pandas dataframe from large list of records: how to make more efficient?
I am creating an epidemiological model which takes inputs and produces outputs. A standard output is a python dictionary with the following information { 'Location': 'Australia', 'Age group': '1 to 4', 'Sex': 'm', 'Cancer': 'cervical', 'Stage': 'stage IV', 'Coverage': 'Covered', 'Year of cohort': 2022, 'Year': 2025, 'Mortality': 0.0 } However, the current model produces 330,000 dictionaries which look like this. I'd like to create a dashboard using this information, which maintains the data in each entry. My first thought was to create the dataframe iteratively as follows: pd.DataFrame([x for x in huge_list_of_dictionaries], index=[0]) This produces the intended result, but takes several minutes to aggregate the data (using my personal computer, intel i7, nothing fancy). The hope is that this data can be used fairly quickly in a webapp using django, so reducing the speed is essential. I have had two thoughts about quicker solutions, Encode the strings as integers (e.g. male sex = 0), then remap the data once in the dataframe, or even when plots are generated. Have an intermediary step where the relevant data is selected (e.g. only prostate cancer) and only return this data Is there a more obvious solution that I am missing? -
I have a problem when I submit product in the cart with AJAX / Django
I can't submit product in the the cart when I use AJAX without refreshing page. When I submit JSONPage will be displayed. I'm trying to use AJAX first. Trying to add product in the cart without refreshing page. I need help please :) Views Django def add_cart(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = CartProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity'], update_quantity=cd['update_qt'] ) return JsonResponse({'status': 'success'}) Form from django import forms from django.core.validators import MinValueValidator, MaxValueValidator class CartProductForm(forms.Form): quantity = forms.IntegerField(initial=1) update_qt = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) HTML Code <form action="{% url "..." %}" method="post" data-id="{{ ... }}" class="form-order" id="form"> {{ cart_product_form }} {% csrf_token %} <a data-id="{{ ... }}" class="buy-product"><button>BUY</button></a> </form> JS Code products = document.querySelectorAll('.buy-product') for (var i=0; i < products.length; i++){ $(products[i]).on('submit', function(){ var product_id = $(this).attr('data-id') var quantity = 1 console.log(product_id) console.log(quantity) data = { 'product_id': product_id, 'quantity': quantity } var point='/cart/add/'+product_id/ $.ajax({ headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, url: point, method: HttpMethod, type: 'POST', data: data.serialize(), success: function(data){ console.log('success') console.log(csrftoken) } }) }) } -
display multiple django messages in one page?
I have a template in which user can change his details like name, email and password. I am getting wrong messages after updating info ( if I change the password then I got message "Invalid" that is part of edit_profile) though I used extra_tags for message to identify two different messages, But still having issue. I tried searching a lot, and found some relevant questions but was not helpful. views.py def edit_profile(request): if request.user.is_authenticated: if request.method == 'POST': form = EditProfileForm(request.POST, instance=request.user) if form.is_valid(): form.save() messages.success(request, "Update successful!", extra_tags='edit_profile') return redirect("accounts:edit_profile") else: messages.error(request, "Invalid", extra_tags='edit_profile') return redirect("accounts:edit_profile") else: form = EditProfileForm(instance=request.user) return render(request, "accounts/edit_profile.html", {'form': form}) else: redirect('accounts:signin') def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() messages.success(request, "Update successful!", extra_tags='change_password') update_session_auth_hash(request, form.user) return redirect("accounts:change_password") else: messages.error(request, "Password Error", extra_tags='change_password') return redirect("accounts:change_password") else: form = PasswordChangeForm(user=request.user) return render(request, "accounts/edit_profile.html", {'form': form}) template <h2 class="font-weight-bolder">Account Details</h2> <!-- edit_profile form --> <form action="{% url 'accounts:edit_profile' %}" method="post" class="row g-3 needs-validation" novalidate> {% csrf_token %} <!-- 1 Username --> <div class="offset-md-2 col-md-4 "> <label for="username" class="form-label">Username</label><br> <input type="text" name="username" class="form-control" id="username" value="{{ form.username.value }}" required> <div class="invalid-feedback"> Please provide name. </div> </div> <!-- 2 Email --> <div class="offset-md-1 col-md-4"> … -
Django Multiple Types of Users, one base usertype?
I am attempting to create a food delivery app clone. Which has two types of users Restaurant User and Customers. I want the restaurant user to be able to also be customers, using the same login info. This is how my models are setup right now: class Restaurant(models.Model): user_name = models.OneToOneField(User, on_delete=models.CASCADE, related_name='restaurant') full_name = models.CharField(max_length=500) phone = models.CharField(max_length=500) employee_id = models.CharField(max_length=500) class Customer(models.Model): user_name = models.OneToOneField(User, on_delete=models.CASCADE, related_name='customer') full_name = models.CharField(max_length=500) email = models.CharField(max_length=500) avatar = models.CharField(max_length=500) phone = models.CharField(max_length=500) address = models.CharField(max_length=500) I don't believe this works as intended. Would it be better to create a base usertype, for login and shared information, like user_name, full_name, phone? I created the following for that purpose: class CustomUser(AbstractUser): user_name = models.OneToOneField(User, on_delete=models.CASCADE, related_name='CustomUser') full_name = models.CharField(max_length=500) phone = models.CharField(max_length=30) But I'm not sure how to connect this between the other user models. Or if this is even the proper way to do it. So how can I achieve what I am trying to do, what would my models look like? -
How to insert Year choices in DateInput Widget?
I have a current widget like this: date_fr= forms.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'})) Which renders a simple datepicker on template (input type=date) However, I dont know how to limit the years. my choices: YEAR_CHOICES = [] years = calendar.get_year(0) #calendar.get_year separate py function to get the years for i, x in enumerate(years): print(x) YEAR_CHOICES.append(([x, x])) My other form: forms.DateField(widget=forms.SelectDateWidget(years=YEAR_CHOICES)) Does limit the years but it separates the month, day and year on three separate select drop downs. -
How to integrate mailinblue in django-python
can someone please tell me how can I integrate sendinblue mail service inside my Django app. I have created a project for e-commerce in which if the user clicks on check out and as soon as he checks out, the mail should be sent to his registered email address and the mail should contain invoice in html format. I know how to do for malign but as its free for 3 month whereas sendinblue gives you lifetime n amount of bulk emails to use. so I want to integrate/configure sendinblue, please help. I Appreciate your time and efforts. -
django.db.utils.DatabaseError when updating upvotes of a post
I've created a reddit-like clone web that accept users upvotes and downvotes for both post and comments, however, I keep getting a databaseError. I am using djongo to connect to my mongodb atlas. Everything is working with djongo until I add the upvote/downvote features. I think that my votes up/down calculation updates are correct, I've updated urls.py. The issue is at self.save(). This is the code for the votable models: class Votable(BaseModel): upvote_count = models.PositiveIntegerField(default=0) downvote_count = models.PositiveIntegerField(default=0) class Meta: abstract = True def get_score(self): return self.upvote_count - self.downvote_count @staticmethod def get_object(eid): post = Post.get_or_none(eid=eid) if post: return post comment = Comment.get_or_none(eid=eid) if comment: return comment def toggle_vote(self, voter, vote_type): uv = UserVote.get_or_none(voter=voter, object_id=self.eid) if uv: # Case 1.1: Cancel existing upvote/downvote (i.e. toggle) if uv.vote_type == vote_type: uv.delete() # Case 1.2: You're either switching from upvote to downvote, or from downvote to upvote else: uv.vote_type = vote_type uv.save() # Case 2: User has not voted on this object before, so create the object. else: UserVote.objects.create(voter=voter, content_object=self, vote_type=vote_type) def get_user_vote(self, user): if not user or not user.is_authenticated: return None uv = UserVote.get_or_none(voter=user, object_id=self.eid) if not uv: return None if uv.vote_type == UserVote.UP_VOTE: return 1 else: return -1 def _change_vote_count(self, vote_type, … -
Generate pdf with bootstrap in django
I'm trying to generate a PDF by providing an HTML page in my Django project. I have previously used the pisa library of xhtml2pdf but failed to load bootstrap. It will be very helpful, if the PDF is not only just a screenshot/image containing page, rather a searchable one. Which alternative can I use now? -
Is modifying Django urlconf via set_urlconf and request.urlconf in a middleware safe?
I am changing the default urlconf in a middleware based on the requested hostname and it's working as expected during development, however I am concerned about racing/threads as I am modifying a Django setting at runtime! My concern is that Django would confuse the urlconfs with many concurrent requests. Is that a valid concern? -
Django transferred from windows to M1 Mac not working
I've recently transferred a small Django Project from my windows machine to my new M1 Mac and when try to run the same project which was working with no issues on windows is showing error like this: (venv) sravan_ss@Sravans-MacBook-Air btre_project % python manage.py runserver File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax Manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'btre.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '3%@q4cyi9v!3#z#w@cp**1vf&22r_+mlrc!%m8ra-pe#$!uoeu' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # ! Warning # ? Should I # TODO: Make this happen # // line of code # * … -
How to make custom primary key in Django models
I'm building an app that show tables of data. The primary key that my client want is like this Year-4digitinteger-3digitinteger Instance: 20200001001 When the last 3 digit number reach 200 it add 1 to 4digit in the middle and back count from 1 again Below is the example: Before: 20200001200 After add one more data: 20200002001 How can i achieve that? -
Python Stomp.py library is returning 403 error while accessing through outside network
I am working on a product which is working on inside company network. Now requirement is use application outside company network. In application we are using python stomp.py plugin for messaging queue. When we accessing application within company network then everything is working fine. But when we trying to access application outside the company network then stomp.py library throwing 403 error. -
Set a reverse foreignkey relationship in django without saving
if you have an instance of a django object, you can set a field and if you don't save it, it goes away. if you have a foreignkey relationship and you use set, clear, etc. the change you made is immediately written to the db. this makes sense, but is there a way not to do this. As in to temporarily modify the relationship objects, similar to what you can do for a charfield, etc. https://docs.djangoproject.com/en/3.1/topics/db/examples/many_to_many/ class Foo(model): name = charfield() class Bar(model): name = charfield() foo = Foreignkey(Foo, related_name="bars", null=True) bar1 = Bar.objects.create(name="bar1") bar2 = Bar.objects.create(name="bar2") foo = Foo.objects.create(id=1, name="dog") foo.bars.add(bar1) foo.bars.add(bar2) foo.name >> "dog" foo.name = "cat" foo.name >> "cat" len(foo.bars.all()) >> 2 foo.bars.clear() len(foo.bars.all()) >> 0 foo1 = Foo.objects.get(id=1) foo1.name >> "dog" len(foo1.bars.all()) >> 0. ---->>>> i want this to remain 2 -
modify the @login_required Decorator in Django to do authentication Role wise - Django, Python
I am working on a project in Django 3.1.2, here I have several models and views, and I have three entities admin, designer and customer. I have created customer and admin site separately, but the designer has some functionalities to modify some files, and entries in database from admin side. I can use @login_required validator to restrict unauthenticated user to access the pages, but I also want to make stop the designer to use all the functionalities of the page which admin can do, so I have taken a field role in user table so that I can easily identify the type of user, but don't know how to use is to create it in decorator so that I don't have to check in every view for the user role. My user models is like given below: models.py class User(AbstractUser): GENDER = ( (True, 'Male'), (False, 'Female'), ) USER_TYPE = ( ('Admin', 'Admin'), ('Designer', 'Designer'), ('Customer', 'Customer'), ) user_id = models.AutoField("User ID", primary_key=True, auto_created=True) avatar = models.ImageField("User Avatar", null=True, blank=True) gender = models.BooleanField("Gender", choices=GENDER, default=True) role = models.CharField("User Type", max_length=10, choices=USER_TYPE, default='Customer') can you please help me to create a role based login required decorator. -
How do I sort a Django queryset by frequency of occurance from a list and ensure the remaining objects follow?
I have a Django application running Django 3+ and Python 3.8+. I am trying to fill the front page of my site with relevant accounts to the user currently logged in. I have a list of common tags (belonging to the logged in user), let's call this: common_tags=['tag1','tag2','tag3'] This list can vary in length. My goal: I need to be able to query all my users and filter it in such a way that I get an ordered queryset where the users who have the most common_tags as their tags come up on top. That set of people need to be sorted by who has more tags in common (not based on how many of each tag they have, just the common occurrences with logged in user). This same query set should also contain the remaining users who do not have any of the common tags. Lastly, this queryset should not have any repeats. So far I have: relevant_accounts= User.objects.all()\ .annotate(count_resources=Count('resources')).order_by('-count_resources')\ .order_by(Case(When(resources__tags__name__in=common_tags, then=0),default=1, output_field=FloatField())) This appears to work, but I get repeated values. Running .distinct() does not resolve the issue. Edit: Sample Input/Output User A: Tags = ['A','A','B','C'] User B: Tags = ['A','B','B','C'] User C: Tags = ['A','B','B','B'] Sample User … -
AWS Elastic Beanstalk an error occured: no such file or directory for a Django/Python3 app
I followed this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html I was able to stand up my Django project on my local MacBook pro, but when deploying to AWS EB, it failed, logs below: 2021/02/03 23:50:45.548154 [INFO] Executing instruction: StageApplication 2021/02/03 23:50:45.807282 [INFO] extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/ 2021/02/03 23:50:45.807307 [INFO] Running command /bin/sh -c /usr/bin/unzip -q -o /opt/elasticbeanstalk/deployment/app_source_bundle -d /var/app/staging/ 2021/02/03 23:50:46.552599 [INFO] finished extracting /opt/elasticbeanstalk/deployment/app_source_bundle to /var/app/staging/ successfully 2021/02/03 23:50:46.553257 [ERROR] An error occurred during execution of command [app-deploy] - [StageApplication]. Stop running the command. Error: chown /var/app/staging/bin/python: no such file or directory 2021/02/03 23:50:46.553265 [INFO] Executing cleanup logic 2021/02/03 23:50:46.553350 [INFO] CommandService Response: {"status":"FAILURE","api_version":"1.0","results":[{"status":"FAILURE","msg":"Engine execution has encountered an error.","returncode":1,"events":[{"msg":"Instance deployment failed. For details, see 'eb-engine.log'.","timestamp":1612396246,"severity":"ERROR"}]}]} My research led me to this post: AWS Elastic Beanstalk chown PythonPath error, but when I tried the suggested command: git rm -r --cached venv in my project directory, it returned: fatal: pathspec 'venv' did not match any files. Any insight would be greatly appreciated! -
Is it good to build SSO app with Django with multiple auth backend?
I'm wondering how good is to build SSO service written in Django with multiple backends (mobile phone + OTP, email + password) using JWT. Is there any best practices and some advices? How Django + Postgres will work together if there will be more than 10 000 users per day. I know all of these are scalable. But, I will be grateful for any architectural advices and recommendations at the beginning. -
'ManyToManyDescriptor' object has no attribute 'all' when accessing related_name
I have 3 models: class Airport(models.Model): code = models.CharField(max_length=3) city = models.CharField(max_length=64) def __str__(self): return f"{self.city} ({self.code})" class Flight(models.Model): origin = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="departures") destination = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="arrivals") duration = models.IntegerField( ) def __str__(self): return f"{self.id}: {self.origin} to {self.destination}" class Passenger(models.Model): first = models.CharField(max_length=64) last = models.CharField(max_length=64) flights = models.ManyToManyField(Flight, blank=True, related_name="passengers") def __str__(self): return f"{self.first} {self.last}" and I am trying to access all passengers of a certain Flight when I visit /<int:flight_id> like this: def flight(request, flight_id): flight = Flight.objects.get(id=flight_id) # return HttpResponse(flight) return render(request, "flights/flight.html", { "flight": flight, "passengers": Flight.passengers # AttributeError: 'ManyToManyDescriptor' object has no attribute 'all' }) Your response is appreciated Thank you In advanced -
How to add a condition in template to detect super user is the same as post author
I am trying to something new in Django Project, I have different blogs made by users but I want to change the name of superusers or staff to become admin instead of their names. I have made a trial but it didn't work accurately I think the correct way would be similar. Here is the template: {% if post.author == user.is_superuser %} <a class="mr-2 proj-title" href="">Admin</a> {% else %} <a class="mr-2 proj-title" href="{% url 'blog:user-posts' post.author.username %}">{{ post.author }}</a> {% endif %} Currently, all users' name appears either superuser or normal users. Question how can I check is the post.author is a superuser or staff and if staff the name should be admin -
Django - Cannot pass id of Django form to javascript variable
So I read the django documentation and a django form field id should have the format id_(form field name), but when I try to reference this id when assigning the form field to a javascript variable it returns null. To test this, I used auto_id to make sure the id I used in javascript matches the field id I am trying to reference and it does. Additionally, I passed another html element ("testid") to my javascript to make sure it works with the rest of the elements in the template and it does. Why would I be able to assign the id of all of my html elements to a javascript variable but not the django form? forms.py (list of choices not included to save space) class FilterForm(forms.Form): dataset = forms.CharField(label='', widget=forms.Select(choices=DATASET_CHOICES)) graph_type = forms.CharField(label='', widget=forms.Select(choices=GRAPH_CHOICES)) html {% extends 'base.html' %} {% load materializecss %} {% block content %} <form action = "", method = "POST"> {{form|materializecss}} </form> {{form.graph_type.auto_id}} <div id = "testid"></div> {% endblock %} main.js const carInput = document.getElementById("id_graph_type") const testInput = document.getElementById("testid") carInput.addEventListener('change', e=>{ console.log('Changed') }) testInput.addEventListener('change', e=>{ console.log('Changed') }) -
How to prompt category specified form in vue js
In first step form we have one field category field. if user enters "Real estate" based on that we need to prompt Real estate form in second step with some input fields like "total rooms", "square ft". if user enters "IT Training" based on that category we need to prompt IT Training form in second step with some input fields like "Location", "Salary". I have tried a lot this by capturing category from first form by using onchange event. I have written one condition but how to call that particular step 2 form after user enters based on that need too prompt user specified form. onChange(event) { var category = event.target.value if (category == "Real Estaste"){ // Here I need to propt real estate form with some fields // example fields are total rooms, square_ft. }, This is an example code of multi step form please help me to achieve this, Thank you. <html> <head> <script src="https://unpkg.com/vue@next"></script> </head> <body> <html lang="en"> <head> <title>Multistep Form In VueJs</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <h3 class="text-success" align="center">Multistep Form In VueJs</h3> <br> <div class="container" id="app"> <div class="panel-group"> <div class="panel panel-primary"> <div class="panel-heading">Multistep Form In VueJs</div> <form class="form-horizontal" action="/action_page.php"> <fieldset v-if="step == 1"> … -
Django Heroku not displaying all images when DEBUG=False
I have deployed my app on Heroku and all works fine when DEBUG=True however when I set this to False some of my images do not show up. They appear on the base.html and the home.html but none of the other pages which I find odd as they use the same path. Here is my static files in settings.py - STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' # # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) I have tried using whitenoise but Heroku has an error when deploying with it. Any advice?