Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My Django is suddenly showing KeyError when I add a new document
My API used to work perfectly whoever now whenever I add a new document I get KeyError message (It didn't do that before and I haven't change anything on my python code :(...) the message is something as follows: KeyError at /domain/ 'jXLTurf56ECMhhbNJB9w' Request Method: POST Request URL: my url Django Version: 4.1.5 Exception Type: KeyError Exception Value: 'jXLTurf56ECMhhbNJB9w' Exception Location: /app/My_API/views.py, line 632, in post Raised during: My_API.views.My_RS_ModelBased Python Executable: Python Version: 3.10.9 I tried deleting whatever new document I added and it started working again -
Where does "AttributeError: 'VendorAlias' object has no attribute 'find_spec'" come from?
I'm currently trying to update a larger codebase from Python 3.8 to Python 3.11. I use pyenv to manage my Python versions and poetry to manage my dependencies: pyenv local 3.11.3 poetry update When I run pytest I immediately get: python -m pytest -n 1 Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 1074, in _find_spec AttributeError: 'VendorAlias' object has no attribute 'find_spec' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/martin/.cache/pypoetry/virtualenvs/web-backend-4tJQ0X3K-py3.11/lib/python3.11/site-packages/django/utils/module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "/home/martin/.pyenv/versions/3.11.1/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 1076, in _find_spec File "<frozen importlib._bootstrap>", line 1049, in _find_spec_legacy ImportWarning: VendorAlias.find_spec() not found; falling back to find_module() During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<frozen importlib._bootstrap>", line 1074, in _find_spec AttributeError: 'VendorAlias' object has no attribute 'find_spec' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "/home/martin/.cache/pypoetry/virtualenvs/web-backend-4tJQ0X3K-py3.11/lib/python3.11/site-packages/pytest/__main__.py", … -
I am getting a TypeError that my Django ChoiceField's choices are unhashable Type: 'list'
I'm new to Django. I use formset and form via TabularInline. First, I'll show you my forms.py code. DISCONN_BLANK = ((None, '---disconnect---'),) CONN_BLANK = ((None, '---connect---'),) class MyFormSet(BaseInlineFormSet): def get_form_kwargs(self, index): kwargs = super(MyFormSet, self).get_form_kwargs(index) kwargs.update({'parent': self.instance}) return kwargs class MyForm(select2_modelform(Conninfo)): class Meta: model = Conninfo fields = ['mgr_id', ] parent_value = None def __init__(self, *args, **kwargs): instance = kwargs.pop('parent') if instance: self.parent_value = instance print('MyFrom __init__ parent_value {}'.format(self.parent_value)) super(MyForm, self).__init__(*args, **kwargs) conn_queryset = tuple(Conninfo.objects.filter(client_id=self.parent_value).values('mgr_id').values_list('mgr_id', 'mgr_id')) disconn_queryset = tuple(Devicemanager.objects.exclude(mgr_id__in=Conninfo.objects.all().values('mgr_id')).values_list('mgr_id', 'mgr_id')) mgr_id_widget = select2_modelform(Conninfo)().fields['mgr_id'].widget choices = DISCONN_BLANK + tuple(disconn_queryset) + CONN_BLANK + tuple(conn_queryset) print(choices) print(type(choices)) self.fields['mgr_id'] = forms.ChoiceField(choices=choices, widget=mgr_id_widget) Does it seem very complicated..? The point is the conn_queryset and disconn_queryset and choices parts. The type of choices is tuple, and when I try to print ((None, '---disconnect---'), (('id1', 'id1'), ('id2', 'id2'), ... ('id10', 'id10'), ( None, '---connect---'), ('id14', 'id14'), ('id15', 'id15')) It comes in the form of a tuple. But what about the results? TypeError at unhashable type: 'list' where is the list? Isn't list {}? I really don't know. And the strange thing is that if you take the last code out of the init function from conn_queryset, it will be executed. Of course, it doesn't give me the … -
Django: Can I use Subquery with more than one database?
I have two 2 tables in different databases. # Database A class Category(models.Model): name = models.CharField(max_length=100) # Database B class Hero(models.Model): # ... name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) benevolence_factor = models.PositiveSmallIntegerField( help_text="How benevolent this hero is?", default=50 ) Can I use Subquery like this: hero_qs = Hero.objects.filter( category=OuterRef("pk") ).order_by("-benevolence_factor") Category.objects.all().annotate( most_benevolent_hero=Subquery( hero_qs.values('name')[:1] ) ) Actually, I found this: https://books.agiliq.com/projects/django-orm-cookbook/en/latest/subquery.html but no example with different databases. -
On using Multipartparser or formparser classes Swagger documentation won't load, the error - "cannot instantiate nested serializer as Parameter"
I am using a nested serializer as shown below - class Documents_ManagerSerializer(serializers.ModelSerializer): class Meta: model = Documents_Manager fields = ['id', 'doc_type', 'doc_name'] class IndexDetailsCreateSerializer(serializers.ModelSerializer): methodology_file = Documents_ManagerSerializer() Factsheet_file = Documents_ManagerSerializer() Indexvalues_file = Documents_ManagerSerializer() class Meta: model = IndexDetails fields = ['id', 'Tab_id', 'Name' ,'methodology_file','Factsheet_file','Indexvalues_file'] I am using parser classes = Multipartparser and formparser to upload files in swagger documentation, following is my views code - @method_decorator(name='create', decorator=IndexDetailsSwagger.create()) @method_decorator(name='partial_update', decorator=IndexDetailsSwagger.update()) class IndexDetailsView(viewsets.ModelViewSet): parser_classes = (MultiPartParser, FormParser) queryset = IndexDetails.objects.filter(Valid=True).all() serializer_class = IndexDetailsSerializer http_method_names = ['get', 'post', 'patch'] def get_serializer_class(self): if self.action in ["create"]: return IndexDetailsCreateSerializer elif self.action in ["partial_update"]: return IndexDetailsPatchSerializer else: return self.serializer_class def retrieve(self, request, *args, **kwargs): try: instance = self.get_object() return super().retrieve(request, *args, **kwargs) except: return Response({"message": "Instance doesnot exists"}, status=status.HTTP_404_NOT_FOUND) def partial_update(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) try: self.get_object() except: return Response({"message": "Instance doesnot exists"}, status=status.HTTP_404_NOT_FOUND) if serializer.is_valid(): if len(serializer.data.keys()) < 2: return Response({"message": "please provide somedata to update"}, status=status.HTTP_400_BAD_REQUEST) else: super().partial_update(request, *args, **kwargs) return Response({"message": "Data updated Successfully"}, status=status.HTTP_200_OK) else: return Response({"message": serilizer_validation(serializer)}, status=status.HTTP_400_BAD_REQUEST) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"message": "data created successfully"}, status=status.HTTP_201_CREATED) else: return Response({"message": serilizer_validation(serializer)}, status=status.HTTP_400_BAD_REQUEST) and following is the swagger auto schema code - … -
Django ORM aggregate tax sum
I have a Django project. There are Store model and Analytics model. I want to calculate taxes sum for each store. Is it possible to aggregate it by Django ORM in one request to DB? Without any loop by stores list? I don't want smth like this: for store in stores: taxes_sum = store.sales_sum*store.tax/100 I want smth like this: taxes_sum = StoreAnalytics.objects.filter(store__user=self.request.user).aggregate( sales_sum=Sum(F("accruals_sum"))*Sum(F("tax"))/100) but each store has its own tax percent (6%, 15%, 20%....) class Store(models.Model): user = models.ForeignKey(User, on_delete=models.PROTECT) name = models.CharField(max_length=128, blank=True, default="", verbose_name="Name") class StoreAnalytics(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE, null=True, related_name="store_id") sales_sum = models.DecimalField( max_digits=10, decimal_places=2, default=Decimal(0), verbose_name="Sales") tax = models.IntegerField( default=6, validators=[MaxValueValidator(20), MinValueValidator(0)], verbose_name="Tax %" ) Is there any methods to calculate taxes sum? -
GET request returning "Authentication credentials not provided" Django REST Framework
I'm trying to test my very-early-development stage Django REST Framework API by retrieving data of a authentication restricted view from Postman. I'm using Djoser and djangorestframework-simplejwt for handling authentication. My initial post request to log in returns two tokens, 'active', and 'refresh' which I think it is expected behavior. But then I try to use the 'active' token to access a login protected view and I get the "detail": "Authentication credentials were not provided." error. I'm passing the token as a 'Header' with Authorization: Bearer <active token>. Why it keeps saying I don't provide auth credentials? How should those be provided? This is my view and settings: settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), } view: class UserItemsViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticated, ] serializer_class = UserSerializer def get_queryset(self): user = self.request.user queryset = user.items.filter(active=True) return queryset -
Cookies set by Django not showing in Firefox and Safari
I recently noticed my Django set cookies in Edge not persisting on refresh and so I tried Firefox. The problem I see here now is that they are not even showing up in the cookies tab and so is the same in Safari. It works fine in Chrome and I must add the page works fine in Firefox as when I send a request the cookie values are visible (I catch them in a middleware). On the other hand Safari does not save them at all making it inconsistent accross all browsers. I am not sure why this is the case but I am using Django for the backend and React for the frontend. This is the line of code for settign the cookie response.set_cookie('auth1',token_header, httponly=True, samesite='None',secure=True, max_age=600) Same occurs with a csrf cookie and I have the following in settings CSRF_COOKIE_SECURE = True CSRF_COOKIE_SAMESITE = 'None' Any ideas of the issue? -
How to configure my django project: Template Does Not Exist Error?
I am new to the Django framework trying to work through a youtube tutorial to better understand. I created a simple blog post webiste, which was working correctly until I attempted to update my urls.py, views.py, and home.html files respectively. Now when I go to to test the URL on my local machine I am returned with a 500 internal server error, which I do not understand. To my belief my project was configured correctly as I had configured all the variables on my settings.py file. I've added my blog name to the INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', '**DrewThe1stBlog**', ], ROOT_URLCONF = 'DrewsBlog.urls':url config Can anyone provide any insight to what I have done wrong. I have tried to debug the code but I am unable to understand the stack trace. Some simple research on Stack Overflow I have tried adding my python path to the the Templates_DIR amongst other things which have not worked. StackTrace below: Environment: > > Request Method: GET > Request URL: http://localhost:8000/ > > Django Version: 4.1.7 > Python Version: 3.8.5 > Installed Applications: > ['django.contrib.admin', > 'django.contrib.auth', > 'django.contrib.contenttypes', > 'django.contrib.sessions', > 'django.contrib.messages', > 'django.contrib.staticfiles', > 'DrewThe1stBlog'] > Installed Middleware: … -
Django web application
I am using django and mysql for web application,web browser storing user visited templates in chache,when user logout from application user is accessing the templates I used never cache to stop browser from caching,problem is it works fine when user logout but before logout also user can't access his visited templates by back button -
Using GCS for media storage on Railway.app
I'm deploying my Django app to Railway.app and am hosting media on GCS (I like the free tier). I've created the service account and received the .json of the credentials. On my local system for dev, I have the .json file in the directory and refer to it like this: GS_CREDENTIALS = service_account.Credentials.from_service_account_file(".gcs_credentials.json") No problems and files upload great. I'm not passing the credentials file through Github (for safety reasons) but now I'm stuck. Is there a way to save this JSON file as an environment variable in Railway.app? For all of my other variables, I'm using django-environ and everything is working great. I just can't find anything online about passing credentials in JSON form to a deployment on Railway. Thank you in advance. -
Where does Django check framework functions live?
The django framework allows you to write your own checks https://docs.djangoproject.com/en/4.2/topics/checks/ but it says nothing about where that code should live and how it is hooked into the check framework. Any ideas on how this is done? -
Django Follow / Unfollow button does not change
I am trying to create a generic social media platform with django. The follow button works functionally, but doesn't text from "follow". The follower and following counts get updated appropriately. You can follow and unfollow people from the button. I just need the text to change. Models.py: class Follow(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='following', related_query_name='follower') followed_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='followers', related_query_name='followed') created_at = models.DateTimeField(auto_now_add=True) Views.py: @login_required def follow(request, username): user_to_follow = get_object_or_404(User, username=username) follow, created = Follow.objects.get_or_create(user=request.user, followed_user=user_to_follow) if not created: follow.delete() return redirect(request.META.get('HTTP_REFERER', 'home')) def unfollow(request, username): user_to_unfollow = get_object_or_404(User, username=username) try: follow = Follow.objects.get(user=request.user, followed_user=user_to_unfollow) follow.delete() except Follow.DoesNotExist: pass return redirect(request.META.get('HTTP_REFERER', 'home')) URLS.py: path('follow/<str:username>/', views.follow, name='follow'), path('unfollow/<str:username>/', views.unfollow, name='unfollow'), Profile.html: {% extends 'base.html' %} {% block content %} <div class="profile"> <h2>{{ user.username }}</h2> <p>Followers: {{ user.followers.count }}</p> <p>Following: {{ user.following.count }}</p> {% if request.user in user.followers.all %} <form method="post" action="{% url 'unfollow' user.username %}"> {% csrf_token %} <button type="submit">Unfollow</button> </form> {% else %} <form method="post" action="{% url 'follow' user.username %}"> {% csrf_token %} <button type="submit">Follow</button> </form> {% endif %} </div> {% endblock %} -
Erro: GET / HTTP/1.1" 404 2281 - Python / Django
Boa noite! Ao tentar executar no terminal: python manage.py runserver, o seguinte erro é apontado: "GET / HTTP/1.1" 404 2281, a aplicação não inicia no navegador, acusando que: Usando o URLconf definido em , Django tentou estes padrões de URL, nesta ordem: type_event.urls admin/ usuarios/ eventos/ O caminho vazio não correspondia a nenhum desses. Revisei toda a parte de urls do projeto, de app por app e não consegui identificar a causa da falha. Tentei ver pelos arquivos estáticos também, mas não identifiquei a divergência. -
NoReverseMatch at /addpost/
I recently finished my schooling on Django, and now im building a simple travel blog website that will serve as a project and a portfolio for my job search. My reverse match was working but all the sudden it throws this error NoReverseMatch at /addpost/ Reverse for 'article_detail' with arguments '('1', '4')' not found. 1 pattern(s) tried: ['article/(?P[0-9]+)\Z'] it looks like my posts in my model are automatically being assigned two IDs as their primary key but my code is only built to take a single PK so im not sure whats going on or how to fix it here? i read about 20 other stack overflow posts with similar questions but im still struggling to see what i need to do to fix this. below i posted my models.py, views.py and urls.py please let me know if you need to see anything else. the error appears to be at the bottom of my post model where redirect for adding a post is. Here is my model from django.db import models from django.contrib.auth.models import User from django.urls import reverse from datetime import datetime, date from ckeditor.fields import RichTextField class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = RichTextField(blank=True, … -
Integrate reCAPTCHA Enterprise with Android apps and Python as Backend
I want to Integrate reCAPTCHA Enterprise on Front-end (Android) and with Back-end Python on Login. I have implemented on Android and perfectly generating reCAPTCHA response. Problem I send reCAPTCHA generated response to Back-end (Django) in HTTP/POST API call to verify on Back-end. On Back-end I call 'https://www.google.com/recaptcha/api/siteverify' and binded the reCAPTCHA response with GOOGLE_RECAPTCHA_SECRET_KEY to verify the user generated reCAPCHA. But I get message [invalid-input-response] reCAPTCHA in response of 'https://www.google.com/recaptcha/api/siteverify' -
Countdown timer in Django
I need a solution for this issue. I want to make a countdown timer where the deadline is taken from database .. Here is my code to take the remaining time exam_model = modelUjian.objects.get(kodeujian=kodeujian) finish_time = datetime.combine(exam_model.date, exam_model.finishtime) current_time = datetime.now().replace(microsecond=0) time_left = finish_time - current_time context = {"time_left":time_left} return render(request,'mulaiujian.html', context) But i don't know how to show it in HTML. I try some method but it's not working .. nothing appear on countdown span below Here is my HTML <div class="card"> <div class="card-body"> <p>Waktu tersisa: <span id="countdown"></span></p> </div> </div> and this is my javascript .. <script> var countdown = { time_left }; // mengambil countdown dari context di views var x = setInterval(function() { var hours = Math.floor(countdown / 3600); var minutes = Math.floor((countdown % 3600) / 60); var seconds = Math.floor(countdown % 60); // menampilkan waktu dalam format hh:mm:ss document.getElementById("countdown").innerHTML = hours + ":" + minutes + ":" + seconds; if (countdown <= 0) { clearInterval(x); document.getElementById("countdown").innerHTML = "Waktu telah habis!"; } else { countdown--; } }, 1000); </script> -
Using list elements in a form in Django template
I have the following form in a Django template. The list prize is a list of numbers defined in my view.py. Specifically, prize is defined to be prize = [0]*total I want to have the elements of prize listed as the default values on user input fields. I have tried to do this with the following code. <form> {% for i in total %} <label for="match_{{ i }}">Enter the prize received for getting {{ i }} matches:</label> <input type="number" name="match_{{ i }}" id="match_{{ i }}" required value="{{ prize.i|default:'' }}"> <br> {% endfor %} </form> While I get no errors, I only get the empty forms with no default values. Any ideas? I have checked that the list prize is rendered correctly as I can print out their values on the webpage fine. -
Django: can I verify email using otp in Django?
I have a question about Django authentication that has been bothering me for days now. Is it possible for a user, before they create an account they pass through these steps? Enter only their email first I send OTP to their email They verify their email using the OTP I then ask for their username, password 1, password 2 Please, if anybody knows whether something like this is possible using the Django REST framework, I would really appreciate an answer. -
Change dockerized Django default app from git ignored .env
I need to modify the default flatpages app which is in django.contrib and tinymce in site-packages. Both in gitignored env directory installed from requirements.txt when Docker is starting. How it should be properly done? Dockerfile; I've tried to pull it out, change imports (a mess) but soon realized it does not make sense as Django is installed from the Docker image.. -
I don't understand how to display clothing sizes in an online store in the format .html on django
ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ how do I make a form that will add this size to the shopping cart when choosing a clothing size. In principle, I wrote all the code, but I don't understand how I can write code in .html to make it all work, I really ask you, I spent about 2 weeks on it views.py @require_POST def cart_add(request , product_id , size): cart = Cart(request) product = Product.objects.get(id=product_id) size_ = get_object_or_404(ProductSizes , id=size) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product , quantity=cd['quantity'] ,size_=size_, override_quantity=cd['override'] ) return redirect("post") def cart_remove(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) cart.remove(product) return redirect('cart:cart_detail') def cart_detail(request): cart = Cart(request) for item in cart: item['update_quantity_form'] = CartAddProductForm(initial={'quantitu':item['quantity'],'update':True}) return render(request, 'cart/detail.html', {'cart': cart}) urls.py app_name = 'cart' urlpatterns = [ path('',views.cart_detail,name='cart_detail'), path('add/<int:product_id>/',views.cart_add,name='cart_add'), path('remove/<int:product_id>/',views.cart_remove,name='cart_remove'), ] cart.py class Cart: def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart # add to cart def add(self, product, size_, quantity=1, override_quantity=False): size_id = str(size_.id) if size_id not in self.cart: if size_.price: self.cart[size_id] = {'quantity': 0, 'price': size_.price} elif size_.off_price: self.cart[size_id] = {'quantity': 0, 'price': size_.off_price} self.cart[size_id]['quantity'] += quantity self.save() self.save() def save(self): self.session.modified = True # remove … -
Migrations error: changes detected but nothing changed in my database
I'm trying to connect my django project with mongodb database, after migrations the changes detected but nothing happen in my database. I'm providing the models.py and setting.py files, if anyone can help me and thank you in advance. models.py from django.db import models # Create your models here. class Task(models.Model): title=models.CharField(max_length=50) description=models.TextField() deadline=models.DateField() done=models.BooleanField(default=False) class Meta: db_table= 'Coll' settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'Mydb', } } DEFAULT_AUTO_FIELD='django.db.models.AutoField' I already installed djongo, and this is my pip list Django 4.2 django-cors-headers 3.14.0 django-grappelli 3.0.5 django-mongodb-engine 0.6.0 django-suit 2.0a2 djangorestframework 3.14.0 djangotoolbox 1.8.0 djongo 1.3.6 grep 0.3.2 mongoengine 0.27.0 Pillow 9.5.0 pip 23.0.1 pipenv 2023.3.20 pymongo 3.12.1 pytz 2023.3 sqlparse 0.4.3 virtualenv 20.21.0 virtualenv-clone 0.5.7 -
How can I connect ready-made layout on Vue with Django?
I made a frontend part of project on Vue.JS 3 and after a time gets a conclusion that I wants to create backend part on Django. Frontend part already written, backend only in the initial stage - they are located in two different directories. How can I connect backend and frontend to realize data exchange? Please give me some advices how solve this problem. With the help of guides , it was not possible to understand the examples beacuse they have slightly different architecture. -
Problem importing a module in django v4.1.7, pydroid3 python v3.9.7
My urls.py and views.py files are in the same directory (my_app), after importing the views.py file from my urls.py file, whenever I try to start the development server I get a module import error: no module named views but when I compile and run the urls.py file I get an import error: attempted relative import with no parent package. This is the code from urls.py: from django.urls import path from . import views urlpatterns = [ path('', index, name='index') ] I tried modifying the import statement for views into: from views import index and that removed the compilation error but not the server error. -
Odd behavior concerning Django's admin page saving files
I have Django 4.1.7 website, served by apache2 on Ubuntu PC. in the .conf file of apache2: Alias /static /mnt/hdd/SIMSY/static/ and Django works as expected. All CSS, JS, Images are loaded just fine. But when adding new object using Django's built-in admin site, the site tries saving the images on /static in the root of Ubuntu (it caused Permission error, then I tried creating that folder in the root and it actually saved the image in that folder). How is Django trying to save in /static while apache2 tells it that /static is /mnt/hdd/SIMSY/static? I assume there is something can be changed in settings.py to solve that, what can be changed? Here is the part of settings.py that has anything to do with static: BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", ]