Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
makemigrations - No changes detected - Django 4.2 only
Well, I was folloging Django Girls Tutorial but using django version 4.2 All was right until I need makemigrations when I created the model. I put the new app "blog" on INSTALLED_APPS in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] Also, I don't think is necessary, but added the register on admin.py: from django.contrib import admin from .models import Post admin.site.register(Post) After adding all this content and installation, I need to execute makemigrations to generate the 0001_initial.py file migration inside ./blog/migrations directory, but it says me the following message: No changes detected Included the name of my app after the makemigrations command, and still changes were not detected I searched this error on internet and tried different migrate variations, but the only one that worked for me was the next one> ./manage.py migrate --run-syncdb Then it worked, I'm using the default django SGDB sqlite3, the database tables were created after this command and after running the server I can use the models as normal. The problem of doing this comes when I want to edit the models, I execute makemigrations and it still doesn't detect changes. The previous command --run-syncdb only works for creating the … -
Django exception process in production mode
I built a inventory management system using Django. When I sale some products, I need to check whether there are enough products in system. I rewrite save function in models.py and raise an exception when quantity is less than 0. I want to get the exception and show it in views.py. However, no details are showed on web when raising an exception. How should I do, or whether there is other method to solve my need? Here is code: # views.py def custom_exception_handler(request, exception): if isinstance(exception, ValueError): import pdb; pdb.set_trace() error_message = str(exception) return render(request, '500.html', context={'error_message': error_message}, status=500) # models.py def save(self, *args, **kwargs): obj = Stock.objects.get(id=self.stock_id.id) left_quantity = obj.quantity - self.quantity if left_quantity < 0: raise ValueError('No enough inventory') defaults = {'quantity': left_quantity, 'update_time': self.consume_time} for key, value in defaults.items(): setattr(obj, key, value) obj.save() super(RepairOutStock, self).save(*args, **kwargs) # settings.py handler500 = 'spare_parts.views.custom_error_view' # 500 error # templates/500.html <!DOCTYPE html> <html> <h2>{{ error_message }}</h2> </html> -
Nginx not working with Docker, Django and Gunicorn
I've been struggling to Dockerize an existing Django app for over a week now and I'm a bit out of ideas how to proceed. I've copied the prod environment and environment setup but I'm still struggling with the last part that is related to Nginx. I'll outline my Docker files and the YML file that brings the app to life. The Django app, the SQL DB, the Redis instance and the CRON server are all working but the last piece of the puzzle is the Nginx container. The docker-compose.yml is: version: '3.8' services: xyz_web: image: xyz-web:latest networks: - xyz_backend volumes: - ../app:/app - xyz_static:/app/static depends_on: - xyz_db - xyz_cache # ports: # - 8000:8000 command: gunicorn xyz_src.wsgi:application --bind :8000 --workers 1 --threads=3 --access-logfile - env_file: - django/.env xyz_cron: image: xyz-web:latest networks: - xyz_backend volumes: - ../app:/app depends_on: - xyz_db - xyz_cache command: cron -f env_file: - django/.env xyz_cache: image: xyz-cache:latest networks: - xyz_backend volumes: - ../build/redis/data:/data command: /bin/sh -c "redis-server --requirepass $$REDIS_CACHE_PASS" env_file: - redis/.env xyz_db: image: xyz-db:latest networks: - xyz_backend volumes: - ../build/mysql/data:/var/lib/mysql - ../build/mysql/mysqld:/var/run/mysqld ports: - 3306:3306 env_file: - mysql/.env xyz_proxy: image: xyz-proxy:latest networks: - xyz_backend volumes: - xyz_static:/app/static ports: - 8000:80 depends_on: - xyz_web networks: xyz_backend: external: … -
Django DB Query for nested models
I have 3 models in my project: User, Device and Report. A user can own several Devices and each Device will provide several Reports. I want to find the latest report for each device for the currently logged in user. My models are currently: class Device(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) device_id = models.CharField(max_length=50) device_name = models.CharField(max_length=100) def __str__(self): return self.device_id class Report(models.Model): device_id = models.ForeignKey('Device', on_delete=models.CASCADE) coordinates = models.JSONField(null=True) fill = models.IntegerField() date = models.DateTimeField() def __str__(self): return str(self.device_id) This query returns all of the Devices and their associated Reports for the logged in user: device_list = Report.objects.filter(device_id__owner__username=request.user) I'm having difficulty in filtering for only the latest report from each device. -
Assign user to a group to specific database
Does anyone know how to assign a user to a group (to a specific database)? Django offical documentation is not really clear about it. What will be the syntax in this case? from django.contrib.auth.models import User from django.contrib.auth.models import Group user = User.objects.using('db').get(pk=1) admin_group = Group.objects.using('db').get(name='admin') # Need to add this to specific database 'db' instead of default admin_group.user_set.add(user) -
ModuleNotFoundError: No module named 'shop'
I'm currently working with a e-commerce django project. After rewriting my code, I can't get to display my shop products due to a "ModuleNotFoundError". It is saying that Module 'shop' is not there but I already ensured the it is declare in the INSTALLED_APPS. Here the traceback: "Exception has occurred: ModuleNotFoundError No module named 'shop' File "C:\Users\msi\Desktop\shop_name_WebPOS_project\shop_name_webpos_project\shop\tests.py", line 4, in from shop.models import Bikes, Category, Item_Category, Gears, Parts, Services ModuleNotFoundError: No module named 'shop'" here's my code for views.py: from django.shortcuts import render, get_object_or_404 from shop.models import Bikes, Category, Item_Category, Gears, Parts, Services here's my installed apps: INSTALLED_APPS = [ 'admin_interface', 'colorfield', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'admin_site', 'authenticate', 'base_app', 'canvas', 'pos', 'shop', ] and here's for the models: from django.db import models from django.conf import settings class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Meta: ordering = ['name'] verbose_name_plural = 'Bicycle Categories' verbose_name = 'Category' class Brands(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Meta: ordering = ['name'] verbose_name_plural = 'Product Brands' verbose_name = 'Brand' class Bikes(models.Model): category = models.ForeignKey(Category, related_name='items', on_delete=models.CASCADE) name = models.CharField(max_length=255) brand = models.ForeignKey(Brands, related_name='bike_brand', on_delete=models.CASCADE, null=True, blank=True) description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='items\shop_bikes', blank=True, null=True) … -
Implementing Custom Groups and Permissions for Organization Members in Django
I'm working on a Django project where I need to implement a feature that allows each organization to create groups and assign custom permissions to the members of those groups. I want to ensure that organization administrators can create specific groups only for their organization and assign limited permissions related to the app's features. My "Organization" model is defined as follows: class Organization(models.Model): name = models.CharField(max_length=64) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='owner_organizations') slug = models.SlugField(unique=True) pic = models.ImageField(upload_to="organizations/pics/", default='organizations/pics/default.png') I also have an "OrganizationMember" model that links users to organizations: class OrganizationMember(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='organization_memberships') organization = models.ForeignKey(Organization, on_delete=models.CASCADE, related_name='members') # Here, I want to figure out how to manage groups and custom permissions for members of each organization. I noticed that Django provides default models for groups (django.contrib.auth.models.Group) and permissions (django.contrib.auth.models.Permission), but I'm not sure how to efficiently implement this feature. How can I proceed to allow administrators of each organization to create groups and assign custom permissions to the members of those groups? I would also like to enable each member to be a part of multiple groups and have additional individual permissions. I would greatly appreciate any suggestions, guidance, or examples on how to tackle this … -
Is it possible to make Django urlpatterns from a string?
I have a list of strings that is used to define navigation pane in a Django layout template. I want to use the same list for view function names and use a loop to define urlpatterns in urls.py accordingly. Example: menu = ["register", "login", "logout"] urlpatterns = [path("", views.index, name="index"),] From the above, I want to arrive at urlpatterns = [ path("", views.index, name="index"), path("/register", views.register, name="register"), path("/login", views.login, name="login"), path("/logout", views.logout, name="logout"), ] I am able to pass the route as str and kwargs as a dict, but struggling with transforming the string into a name of a callable views function. Is this possible? for i in menu: url = f'"/{i}"' #works when passed as parameter to path() rev = {"name": i} #works when passed as parameter to path() v = f"views.{i}" #this does not work v = include(f"views.{i}", namespace="myapp") #this does not work either urlpatterns.append(path(url, v, rev)) -
Wagtailing include a inline panel (one to many) relationship within the site settings
I am looking to extend the site settings for a Wagtail Project so that the admin can add instances where they were published. That will be used to populate several places around the site, but namely the footer. I feel like my solution below is fairly janky. I seem not be be able to access the setting values in a django template or maybe I not not attacking it the right way. My approach feels like it isn't great here. Any help is appreciated! class Publication(Orderable): page: ParentalKey = ParentalKey("home.PublishedBy", on_delete=models.CASCADE, related_name='publications') name: CharField = models.CharField(max_length=100) url: URLField = models.URLField(blank=True, null=True) image: OneToOneField = models.OneToOneField(Image, related_name='+', on_delete=models.CASCADE) @register_setting class PublishedBy(BaseGenericSetting, ClusterableModel): panels: list[MultiFieldPanel] = [ MultiFieldPanel( [ InlinePanel('publications', label="Publications", min_num=1, max_num=7) ] ) ] -
How can I create a RESTful API using Python and a web framework like Flask or Django?
I'm looking to develop a RESTful API using Python, and I'm considering using web frameworks such as Flask or Django to facilitate the process. The primary goal is to expose a set of endpoints that allow clients to interact with my application over HTTP in a RESTful manner. -
How to deploy Django run with Docker compose to Cloud linux server cpanel use set app python?
I tried to deploy Django admin use Docker and Postgres Database to my cpanel use set app python but the project not run, can any body help with the process of how cam make this deployment? Also I could not able to install the Django site-packages use pip instal in venv. -
program gets stuck when sending email via gmail
I have the following python function: import smtplib, ssl port = 465 # For SSL password = "valid password" context = ssl.create_default_context() def sendEmail(to_email, subject, content): from_email = "valid_email@zaliczenie.pl" message = (f"Tresc zadania: {content}",) try: print("connecting") with smtplib.SMTP_SSL("smtp.gmail.com", port, context=context) as server: print("connected") server.login("tmp_email@gmail.com", password) print("logged") server.sendmail( to_addrs=to_email, from_addr=from_email, msg=message, ) print("sent") except Exception as e: print(e.message) And here are the logs: connecting connected logged So it connects, logs into google mail, but gets stuck when trying to send an email. What am I missing? I allowed the less safe applications and password is the one generated from google security 2FA tab (App passwords). -
Why am I getting a CSRF token missing error when the token is there?
I have a Vue app and I am making requests to a Django Rest Framework endpoint, well a few. It was working fine yesterday and I was able to submit and save content. Today I keep getting the same error CSRF Failed: CSRF token missing. But if I look in the dev tools I see this: |csrftoken|“wzWBo6N66F1HTp2To67We5GppNWfbXdm”| |sessionid|“1vq4vj73b1b6l80gt2ckba6zwxqj8wwu”| So how is it missing if it is right there? Second question: What is the use of this setting if no matter what it still gives you a CSRF error? CORS_ORIGIN_WHITELIST = (“localhost:8080”,“127.0.0.1:8080”) CSRF_TRUSTED_ORIGINS = [“http://localhost:8080”, “http://*.127.0.0.1”, “http://127.0.0.1:8080”,“http://192.168.1.44:8080”,] -
Django: rendering a model object as an image/icon
I have the following two Django models: class ProjectType(models.Model): name = models.CharField("Name", max_length=300, unique=True) class Project(models.Model): name = models.CharField("Name", max_length=300, unique=True) project = models.ForeignKey("ProjectType", on_delete=models.CASCADE) The ProjectType object would be things like: "research", "outreach", "administrative", etc. What I'd like to do is render ProjectType as a standardized icon (ex.: a little beaker representing "research" projects). Perhaps using a method? For instance, having the following line in an HTML template: {{ projet.project_type.as_icon }} And rendering it as: <img src="images/beaker_icon.png"/> Is this possible? Can I give the class method instructions on how to render images? If so, would this be a best practice? -
Form with hidden field not submitting
I have the following form in django forms.py class CtForm(ModelForm): class Meta: model = Contact fields = ["cid", "name", "email"] widgets = {'cid': HiddenInput()} models.py class Contact(models.Model): cid = models.ForeignKey(Cr, on_delete=models.CASCADE) name = models.CharField(max_length=255, null=False) email = models.EmailField(max_length=255, null=False) I have the form displayed in a template, and everything displays good and no issues there, the issue is when i submit the form, i get the following error: (Hidden field cid) This field is required. But if i remove the widgets = {'cid': HiddenInput()} from the forms.py it works perfect, any way to make this work without displaying the cid in the template? -
Django channels: Save messages to database with duplicates when two or more tabs opened
I'm using this solution for save messages to DB Django channels: Save messages to database But I have a problem with duplicates (in DB) when the user (message's author) has two or more tabs opened in the browser with same chat room. What's wrong? Please help! import json from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer from .models import Message class ChatConsumer(AsyncWebsocketConsumer): @database_sync_to_async def create_chat(self, msg, sender): return Message.objects.create(sender=sender, msg=msg) async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add(self.room_group_name, self.channel_name) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard(self.room_group_name, self.channel_name) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] sender = text_data_json['sender'] await self.channel_layer.group_send(self.room_group_name, { 'type': 'chat_message', 'message': message, 'sender': sender }) async def chat_message(self, event): message = event['message'] sender = event['sender'] new_msg = await self.create_chat(sender, message) # It is necessary to await creation of messages await self.send(text_data=json.dumps({ 'message': new_msg.message, 'sender': new_msg.sender })) -
Django Forms - Many to Many relationships with quantity in form
I have three models: 'Product,' 'Vehicle,' and 'VehicleStock.' I'm attempting to create a form for adding a new 'Vehicle.' This form should allow the specification of the 'registry,' 'brand,' and 'stock' (which is a ManyToMany field). Additionally, I'd like to specify the quantity of products associated with the vehicle. I've already tried using 'inlineformset_factory,' but it's not meeting my requirements. It creates a widget where you need to specify every product in the database. Instead, I want a widget that functions like 'add product,' enabling the addition of multiple product widgets for the same vehicle. How can I achieve this?" models.py class Product(models.Model): name = models.CharField(max_length=50) SKU = models.CharField(max_length=20, unique=True) price = models.DecimalField(max_digits=10, decimal_places=2) stock = models.IntegerField() def __str__(self): return f'{self.name}' class Vehicle(models.Model): registry = models.CharField(max_length=20, unique=True) brand = models.CharField(max_length=50) total_kilometers = models.IntegerField() stock = models.ManyToManyField(Product, through='VehicleStock') def __str__(self): return f'{self.registry}' class VehicleStock(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) quantity = models.IntegerField() forms.py class VehicleForm(forms.ModelForm): class Meta: model = Vehicle exclude = ["total_kilometers"] registry = forms.CharField( label='Veic registry', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Registry'}), required=True, error_messages={'required': 'Please enter a Registry.'} ) brand = forms.CharField( label='Veic Brand', widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Enter Brand'}), required=True, error_messages={'required': 'Please enter a brand.'} ) base.html … -
auto move to cart function
We are trying to figure how to move the auction item to the cart. We have our program removing the auction from the auction listing page, however we haven't gotten it to to move to the highest bidders cart. Here is our auction_details function, mycart function auctions_details def auction_details(request, auction_id): auction = get_object_or_404(Auction, id=auction_id) if request.method == 'POST': bid_form = BidForm(request.POST) if bid_form.is_valid(): bid_amount = bid_form.cleaned_data['bid_amount'] if bid_amount > auction.current_bid: # Update the auction details auction.current_bid = bid_amount auction.highest_bidder = request.user Bid.objects.create(bidder=request.user, auction=auction, amount=bid_amount) messages.success(request, f'Your bid successfully is placed at {timezone.now()}!') messages.success(request, f'The auction will expire at {auction.end_date}!') messages.success(request, f'Expired? {auction.end_date <= timezone.now()}!') if auction.end_date <= timezone.now(): auction.ended = True cart_item, created = CartItem.objects.get_or_create(user=auction.highest_bidder, auction=auction) cart_item.quantity = 1 cart_item.save() auction.save() return redirect('auction_details', auction_id=auction.id) else: messages.error(request, 'Bid must be higher than the current bid.') else: bid_form = BidForm() return render(request, 'auctions/auction_details.html', {'auction': auction, 'bid_form': bid_form}) mycart fuction - def mycart(request): if request.user.is_authenticated: cart_items = CartItem.objects.filter(user=request.user) else: cart_items = [] total_amount = 0 # Initialize total amount to zero for item in cart_items: total_amount += item.auction.current_bid * item.quantity context = { 'cart_items': cart_items, 'total_amount': total_amount, # Pass the total_amount to the template } return render(request, 'auctions/mycart.html', context) We think there is … -
trying to add vote feature to my projcet & i'm adding 1 vote, how can check user already added or not and how can i save their data into database
Here is my model : class Vote(models.Model): answer = models.ForeignKey(Answer, on_delete=models.CASCADE, blank=False) author = models.ForeignKey(User, on_delete=models.CASCADE, blank=False) def __str__(self): return str(self.answer) here is my serializer : class VoteSerailizer(serializers.ModelSerializer): class Meta: model = Vote fields = '__all__' here is my views : @api_view(['POST']) @permission_classes([IsAuthenticated]) def upvote(request, pk): answer = get_object_or_404(Answer, id=pk) if answer['author'] == request.user: return Response({ 'error':"You cannot vote twice." }) answer.votes += 1 answer.save() return Response({ 'details':'Vote added' }, status.HTTP_202_ACCEPTED) It shows error "TypeError: 'Answer' object is not subscriptable" in my views loop. and i need to add author and answer in my database ie. model, how can i do that -
How to check for data entered on a form, on a website in the admin interface when using django
I can't seem to see the data entered in the form on my website when I am logging into the Django admin interface. I am expecting the information entered in the form to show in the admin interface or to at least see where the data is being saved. -
Modal bootstrap5 is not working in django app
i want to display the information of contents that retrieved from the database as table in django template, so i used modal bootstrap, the template below: **template.html: ** <!DOCTYPE html> <html dir="rtl" lang="ar"> <head> {% load static %} <title>الواردة المركزية</title> {% load bootstrap5 %} {% bootstrap_css %} <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </head> <body> <table id="tblToExcl" class="table table-striped table-bordered table-sm"> <thead class="thead-dark"> <tr> <th>رقم الكتاب</th> <th>تاريخ</th> <th>تاريخ الاضافة</th> <th>ملاحظات</th> <th>اﻻجراء</th> </tr> </thead> <tbody> {% for doc in docs %} <tr> <td>{{ doc.number }}</td> <td>{{ doc.date }}</td> <td>{{doc.created_at}}</td> <td>{{ doc.note }}</td> <td>{{ doc.status }}</td> <td> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#item-modal" data-item-id="{{ doc.id }}">View details</button> </td> </tr> {% endfor %} </tbody> </table> <script> $(document).ready(function() { $('#item-modal').modal({ show: false, }); $('#item-modal').on('show.bs.modal', function(event) { var itemId = $(event.relatedTarget).data('item-id'); $.ajax({ url: '/item-modal/' + itemId, success: function(data) { $('#item-modal .modal-body').html(data); }, }); }); }); </script> </body> </html> and modal.html: <div class="modal fade" id="item-modal" tabindex="-1" role="dialog" aria-labelledby="item-modal-label" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="item-modal-label">Item Information</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="row"> <div class="col-6"> <p>Item name:</p> <p>{{ item.name }}</p> </div> <div class="col-6"> <p>Item … -
Debug forever pending Celery task calling OptaPy
I try running OptaPy in a Celery task from within a Django application using Redis as a broker. The task is received by the Celery worker, but remains PENDING forever and returns no result. If I set CELERY_TASK_ALWAYS_EAGER = True for debugging, the code runs fine, but synchronously. What could be the issue? Which steps can I take to find out? As OptaPy is a Python wrapper for a Java library, I suspect that Celery might not handle the additional thread well, but I don't know how to debug or fix this. This is the Celery task in question, additional code can be provided on request: @shared_task() def schedule_task(): solver_config = optapy.config.solver.SolverConfig() \ .withEntityClasses(Lesson) \ .withSolutionClass(TimeTable) \ .withConstraintProviderClass(define_constraints) \ .withTerminationSpentLimit(Duration.ofSeconds(30)) solution = solver_factory_create(solver_config) \ .buildSolver() \ .solve(generate_problem()) return str(solution) -
The window for selecting a Google account does not open
I made my site in Python Django and did authentication through django social auth (googleOauth2) and made a webView application for my site in Android Studio, when authenticating through the WebView application, the window with the choice of account does not open (Select an account), it asks for credentials as login and password. How can I make a window open to select an account? -
Django-allauth and subdomains
I have a website site.com with many subdomains (a.site.com ... z.site.com), all this subdomains are handled without using Django Sites framework. I want to add django-allauth for all my domains. Now I have only one Site entry in database (domain: site.com, name: My Site). If users is in a subdomain x.site.com and tries to reset password or link his facebook account, will allauth use my current subdomain in redirects, callback url, restore password links etc or will it use default url from Sites framework? I just hope that I don't have to create separate Site entry for each subdomain. Or will I have to? -
react + django deployment, the problem is static files 404 error
I've tried to deploy django project using react as front-end. I did 'npm run build' in react and i moved all the files builded to 'client' folder in django project like this enter image description here And i changed all the 'href' in 'link' and 'script' tags to ./ like <link rel="icon" href="./favicon.ico" /> <link rel="manifest" href="./manifest.json" /> <script defer="defer" src="./static/js/main.a1de6b00.js"></script> in index.html in 'client' folder. in the setting.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'client')], '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', ], }, }, ] I changed dirs of templates and STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'client/static') ] DEBUG = False I also changed static root and staticfiles_dirs and debug and in mysite/url.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.views.generic import TemplateView urlpatterns = [ path('',TemplateView.as_view(template_name="index.html"), name='index'), path('admin/', admin.site.urls), path('api/', include('api.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I added a line of code for '' But when i run 'python manage.py runserver', it seems there is still problems to load static files like enter image description here Can you guys let me know what to solve the …