Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to solve it when i get 'pythn is not found' as message?
hello everyone i hope you're all doing great basically i start developing in python using django , and for the editor im using VScode , i did already install python,django,pip and all of what is necessary in the terminal but i have a problem when try execute a command in the terminal using python (ig: python .\manage.py makemigrations) i get this message (Python cannot be found. Execute without argument to proceed) and literally i couldn't find any solution to this problem in the intrnet , i hope i can find some answers ps: i have windows 10 as ES thanks for everyone -
Django tag showing errors in html
I have this block of code in my django project: <div class="avatar-preview"> <div id="imagePreview" style="background-image: url({{ request.user.img_url }});"> </div> In Virtual Studio Code, it returns these errors: VSCODE PROBLEMS IMAGE But it's actually working, I mean, like the 'syntax' is wrong but the code works, the image is displayed correctly. How can I get rid of these errors? -
what is wroung in this code after data in this view?
I'm trying to save values in respected model by it shows error like this: File "/home/bikash/tt/nascent/nascent_backend/home/views.py", line 72, in dispatch user.save() AttributeError: 'NoneType' object has no attribute 'save' class CheckoutSessionView(TemplateView): def dispatch(self, request, *args, **kwargs): if request.method == 'POST': price1 = request.body price2 = price1.decode('utf-8') price11 = json.loads(price2) print(price11) print(type(price11),990, price11['json_data']['priceId']) password1 = price11['json_data']['password1'] password2 = price11['json_data']['password2'] name = price11['json_data']['name'] company = price11['json_data']['company'] contact = price11['json_data']['contact'] email = price11['json_data']['email'] user = User(name = name, username = company, email = email, contact=contact ) if password1==password2: user = user.set_password(password1) user.save() company = Company(title = company) company.owner = user company.save() company.members.add(user) how can i save this? -
Return something that is not a part of any model in Generics.listAPIView
How do you format data returned from the Generics.ListAPIView class before sending it to the front end? I want to add metadata to the return value, but I can't add any metadata that isn't already part of a model. For instance: class someList(generics.ListAPIView): serializer_class = someSerializer def get_queryset(self): return someQueryset() class someListSerializer(SurveySerializer): class Meta: model = someListModel fields = ['modelField'] class someListModel(Base): modelField=models.TextField(default="", blank=True) This would yield [{modelField:information},{modelField:information},{modelField:information}] What if I want [ {modelField:information, informationCalculatedFromQueryset:butNotPartOfModel}, {modelField:information, informationCalculatedFromQueryset:butNotPartOfModel},{modelField:information, informationCalculatedFromQueryset:butNotPartOfModel} ] informationCalculatedFromQueryset is not part of someListModel, so I can't just add it into fields. How do I manually append this information to the front end? Is this possible? -
How to display search results with ajax in django project?
I am working in a Django project where one of the functionalities will be that user could search a name (using a form), the view will search that name in database (after some transformation), and the results will be displayed below the form. At the moment, It is necesary that the entire page loads every time a search is submitted. I am working in apply ajax to make this dynamic. The problem is that when I return the search result as a JsonResponse, I am not able to see the data in the success function of ajax. Views.py def indexView (request): form = FriendForm () friends = Friend.objects.all () return render (request, "index.html", {"form": form, "friends": friends}) def searchFriend(request): if request.method =="POST": form = FriendForm (request.POST) if form.is_valid(): if request.is_ajax(): name = form.cleaned_data['name'] query = Friend.objects.filer(first_name__contains=name) print(query) return JsonResponse(list(query), safe=False) else: return JsonResponse(form.errors) Main.js $(document).ready(function() { $("#form1").submit(function() { // catch the form's submit event var search = $("#searchField").val(); $.ajax({ // create an AJAX call... data: $(this).serialize(), // get the form data method: 'post', dataType: 'json', url: "search/ajax/friend/", success: function(data) { // on success.. console.log(data) } }); return false; }); }); -
Django admin returns forbidden after saving in model
I have deployed my Django application using Apache with mod-wsgi and Nginx. However, when I try to add items using Django admin and after saving then it redirects me to a forbidden page like " You don't have permission to access /admin/core/item/ on this server". I have tried with permission solution and I gave my folder permission 777 but nothing changed. -
in django how to add data from html table without using form.py
how to save data from html table in django without using form.py. I am currently creating table in html with add button and after adding all rows in table i want to save it but i am not using form.py only view.py,html,model.py views.py school_name = request.POST['school_name'] m_pass_out = request.POST['m_pass_out'] medicalschool = MedicalSchool(school_name=school_name, m_pass_out=m_pass_out) medicalschool.save() models.py class MedicalSchool(models.Model): school_name = models.CharField(max_length=100) m_pass_out = models.DateField(max_length=100) doctor_profile = models.ForeignKey(DoctorProfile, on_delete=models.CASCADE) created_at = models.DateTimeField() updated_at = models.DateTimeField(blank=True, null=True) class Meta: db_table = 'medical_school' html <div class="container-lg"> <div class="table-responsive"> <div class="table-wrapper"> <div class="table-title"> <div class="row"> <div class="col-sm-8"> <h2>Medical School</h2> </div> <div class="col-sm-4"> <button type="button" id="medical" class="btn btn-info add- new"><i class="fa fa-plus"></i> Add New</button> </div> </div> </div> <table id="medicaltable" class="table table-bordered"> <thead> <tr> <th>Name of School</th> <th>Year of Graduation</th> <th>Actions</th> </tr> </thead> <tbody> <tr> <td id="medicaltext" name="school_name"></td> <td id="medicaldate" name="m_pass_out"></td> <td> <a id="medicaladd" class="add" title="Add" data- toggle="tooltip"><i class="material-icons">&#xE03B;</i></a> <a id="medicaledit" class="edit" title="Edit" data- toggle="tooltip"><i class="material-icons">&#xE254;</i></a> <a id="medicaldelete" class="delete" title="Delete" data- toggle="tooltip"><i class="material-icons">&#xE872;</i></a> </td> </tr> </tbody> </table> </div> </div> </div> -
Delete wordpress on website and replace it with django - Setting up website entirely with django
I own a webpage which has wordpress.org preinstalled. I have never done anything with it, but now it's about time. As I'm learning django, I would like to build my webpage with it instead of using the preinstalled wordpress. How do I go about it? I haven't found anything related to this topic searching the internet. This is the webpage with preinstalled wordpress I'm talking about. -
Can anyone explain why I am getting this exception?
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Trying to find the ImproperlyConfigured error in Django
I know this error has been asked a lot, but I read lots of posts, but I couldn't find the solution to my problem. Can anyone please help me identify where is my error? It keeps appearing the following error: django.core.exceptions.ImproperlyConfigured: The included URLconf 'outside_world.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. outside_world\urls.py: from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path(r'admin/', admin.site.urls), path(r'', views.detail, name='detail'), path(r'trip/', include("trip.urls")), ] trip\urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] trip\views.py: from django.shortcuts import render from django.http import HttpResponse def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) When I remove path(r'trip/', include("trip.urls")), from outside_world\urls.py, it works perfectly, but I need to maintain this line. -
django.db.utils.ProgrammingError: relation does not exist
I developed a Django application deployed on DigitalOcean's Ubuntu server with Postgres db. Everything worked fine, without any problems, but today after adding new model, I'm getting this error: relation "documents_app_document" does not exist although I have this model, where some of my models inherits from Document model. But somehow it was deleted from database, and now I can't add it back to database after migration. How can I add that model as a table again to database ? -
why the form is invalid on post
I have records in my model. I want to list the existing records and edit and add more records. I successfully got the records to my template and edit. I can add new records also. it is working fine in template. But when I post the form is invalid and print invalid message as per my code http response. I can not figure out what is the mistake. Please advise. forms.py: class NewTransForm(forms.ModelForm): th_no = forms.DecimalField(max_digits=5,error_messages={"max_digits":"Transaction number should be less than 6 digits.","unique":"Transaction number already exists."}) class Meta: model = TransHeader fields = ['th_no','th_dt','th_type', 'th_code','th_cust_code','th_sm_code','th_ref'] ... urls.py: path('edit_sales_transaction_details/<int:trans_id>/',views.EditSalesTransaction, name="edit_sales_transaction"), views.py: def EditSalesTransaction(request,trans_id): # template_name= "wstore/edit_sales_transheader_input.html.html" # trans_id =kwargs['trans_id'] if request.method == "POST": print(request.POST) form = NewTransForm(request.POST) if form.is_valid(): # trans_id =kwargs['trans_id'] exist_trans_header = TransHeader.objects.get(id=int(trans_id)) TransBody.objects.filter(trans_header=exist_trans_header).delete() exist_trans_header.delete() obj = form.save() books = request.POST.getlist('book_code') quantities = request.POST.getlist('quantity') prices = request.POST.getlist('price') for book_code,quantity,price in zip(books,quantities,prices): try: book = TextBook.objects.get(code=book_code) TransBody.objects.create(trans_header_id=obj.id,quantity=quantity,price=price,book=book) except Exception as e: print(e) if request.POST.get('save_home'): return redirect('saltransactions') else: print(NewTransForm.errors) # return redirect(reverse('view_sales_transaction', kwargs=kwargs['trans_id'])) return HttpResponse("form is invalid.. this is just an HttpResponse object") else: form = NewTransForm() context = {} # trans_id =kwargs['trans_id'] context['trans_header'] = TransHeader.objects.get(id=int(trans_id)) trans_body = TransBody.objects.filter(trans_header=context['trans_header']) context['trans_body'] = trans_body context['total_quantity'] = trans_body.aggregate(Sum('quantity')) context['total_price'] = trans_body.aggregate(Sum('price')) context['current_date'] = datetime.datetime.strftime(datetime.datetime.now(),"%Y-%m-%d") … -
How to implement carousel in django with col-md?
I would like to load django model instance in a js carousel with col-md. How should i do that? -
Django pre-save
I'm working on my first project with Django ,it's a personal blog the story model has 'beginning' filed that is first 100 characters of the story itself I want to create beginning with pre_save but I got error always : in admin section when I add a story and leave the beginning blank ,Django say 'this field is required'!! this works very good in another file here is the code : from django.db import models from django.db.models.signals import pre_save from my_blog_tags.models import Tag # Create your models here. class Story(models.Model): title = models.CharField(max_length=75) story = models.TextField() beginning = models.CharField(max_length=100) tags = models.ManyToManyField(Tag, blank=True) active = models.BooleanField(default=True) views = models.IntegerField(default=0) def __str__(self): return self.title class Meta: verbose_name = "story" verbose_name_plural = "stories" def story_pre_save(sender, instance: Story, *args, **kwargs): if not instance.beginning: story = str(instance.story) instance.beginning = story[:100] pre_save.connect(story_pre_save, sender=Story) -
I am getting LocalUnboundError
This is my views.py file: url = "https://covid-193.p.rapidapi.com/statistics" headers = { 'x-rapidapi-key': "c5e4f10fa8msh519e24367741e55p1dcabajsn27df4eda14e0", 'x-rapidapi-host': "covid-193.p.rapidapi.com" } response = requests.request("GET", url, headers=headers).json() def home(request): noofresults = int(response['results']) mylist = [] for x in range(0,noofresults): mylist.append(response['response'][x]['country']) if request.method=='POST': selectedcountry= request.POST['selectedcountry'] # noofresults = int(response['results']) for x in range(0,noofresults): if selectedcountry==response['response'][x]['country']: new = response['response'][x]['cases']['new'] active = response['response'][x]['cases']['active'] critical = response['response'][x]['cases']['critical'] recoverd = response['response'][x]['cases']['recovered'] total = response['response'][x]['cases']['total'] deaths = int(total)-int(active) - int(recoverd) context = {'selectedcountry':selectedcountry,'mylist':mylist, 'new':new, 'active':active, 'critical':critical, 'recoverd':recoverd, 'total':total, 'deaths':deaths} return render(request,'home.html',context) context = {'mylist': mylist} return render(request, 'home.html',context) The error i am getting after selecting a country is: UnboundLocalError at / local variable 'new' referenced before assignment -
How to Fix no reverse match with argument in django
I have the following error in Django, I'm new to Django and i Cant seem to figure where the error is coming from. no tutorial seems to help either. I have a feeling the error might be coming from urls.py but cant seem to navigate it where do you think the error is? NoReverseMatch at / Reverse for 'subcategory_detail' with arguments '('DEFAULT VALUE',)' not found. 2 pattern(s) tried: ['category/(?P<category_slug>[\\w-]+)/$', '$'] Here is my models.py from django.db import models from django.urls import reverse from django.utils.text import slugify from datetime import datetime class Category(models.Model): title = models.CharField(max_length=30, default="Random") slug = models.SlugField(max_length=100, unique=True, blank=True, null=True) category_thumbnail = models.CharField(max_length=400, default='DEFAULT VALUE', blank=True, null=True) category_description = models.CharField(max_length=400, default='DEFAULT VALUE', blank=True, null=True) def __str__(self): return self.title class Meta: verbose_name_plural = "Categories" def get_absolute_url(self): return reverse("subcategory_detail", args=[self.slug]) class SubCategory(models.Model): title = models.CharField(max_length=30, default="Random") categories = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) slug = models.SlugField(max_length=100, unique=True, blank=True, null=True) subcategory_thumbnail = models.CharField(max_length=400, default='DEFAULT VALUE', blank=True, null=True) subcategory_description = models.CharField(max_length=400, default='DEFAULT VALUE', blank=True, null=True) def __str__(self): return self.title class Meta: verbose_name_plural = "SubCategories" class Tag(models.Model): name = models.CharField(max_length=100, unique=True, blank=True, null=True) slug = models.SlugField(max_length=100, unique=True, blank=True, null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('lesson_by_tag', args=[self.slug]) class Lessons(models.Model): title = models.CharField(max_length=200) slug … -
Adding schema name to media path for django-tenant based site
I have a Django class that I use to save my media directory to Azure. This uses Django-tenants https://github.com/django-tenants/django-tenants and I need to return the name of the schema to the media path. When I want to run this locally, if I change the DEFAULT_FILE_STORAGE = "django_tenants.files.storage.TenantFileSystemStorage" the media files are saved as media/schema_name. But if I use Azure it ommits the schema name. stroages.py from storages.backends.azure_storage import AzureStorage from django_tenants.files.storage import TenantFileSystemStorage class AzureMediaStorage(AzureStorage, TenantFileSystemStorage): account_name = settings.AZURE_ACCOUNT_NAME account_key = settings.AZURE_STORAGE_KEY azure_container = settings.AZURE_MEDIA_CONTAINER expiration_secs = 30 overwrite_files = True Settings.py: DEFAULT_FILE_STORAGE = 'saleor.core.storages.AzureMediaStorage' STATICFILES_STORAGE = "django_tenants.staticfiles.storage.TenantStaticFilesStorage" MULTITENANT_RELATIVE_MEDIA_ROOT = " -
How exactly do django serializers and views work together? And how can I return additional data with my queryset to the frontend?
I'm working with a react front end and a django rest framework backend, and I'm having trouble understanding what happens in between the view and the serializer. I want to return additional metadata that is not part of the queryset to the front end. Here is the flow of my application My frontend calls an endpoint: Server.get("api/books-filtered") This goes to a path in the backend written with django rest framework: path("books-filtered/", Books.BookList.as_view()), and then to class Books(generics.RetrieveAPIView): serializer_class = BookSerializer lookup_field = 'id' lookup_url_kwarg = 'book_id' def get_queryset(self): """Return only queries pertaining to the patient""" return FilterOutSomeBookRelatedQuerySetHere() whose serializer class is: class BookSerializer(SurveySerializer): class Meta: model = Book fields = ['Title','Author','Publisher'] I get this back on the front end: console.log(Server.get("api/books-filtered")) // prints [{Title:"book 1", Author:"author 1", Publisher:"publisher 1"},{Title:"book 2", Author:"author 2", Publisher:"publisher 2"},{Title:"book 3", Author:"author 3", Publisher:"publisher 3"}] What happens between the view and the serializer that causes the data to be formatted like that by the time its sent back to the frontend? How can I modify what gets printed by console.log(Server.get("api/books-filtered")) to include additional metadata? Like console.log(Server.get("api/books-filtered")) // prints [{Title:"book 1", Author:"author 1", Publisher:"publisher 1"},{Title:"book 2", Author:"author 1", Publisher:"publisher 2"},{Title:"book 3", Author:"author 1", Publisher:"publisher 2"}, [3 books, 2 … -
Django app custom clean up for code reload
my Django project has an app which overrides its AppConfig.ready() method. In the ready method, I'm starting a separate multiprocessing.Process to handle consuming from an external message queue, this seems to be causing problems with autoreload on code changes. def infinite_loop(): while True: time.sleep(10) class BrokerConfig(AppConfig): name = 'backend.broker' has_started = False def ready(self): if not os.environ.get("RUN_MAIN"): # Avoid running for reloader return if BrokerConfig.has_started: return BrokerConfig.has_started = True proc = Process(target=infinite_loop) proc.start() For whatever reason, this causes the automatic code reload to break. Seems the reloader is not able to clean up started processes. The reloader prints this and then gets stuck: .../backend/broker/apps.py changed, reloading. I run into exactly the same issue if I start a threading.Thread instead of a multiprocessing.Process. I am looking for some way to add some custom clean up when the reloading is happening, but I can't seem to find a way to do that. Is there some hook or signal you can subscribe to in order to find out if reloading has been triggered? Alternatively, I need to find another solution to subscribing to message queues. I was looking at Django Channels, but it did not look like they had built-in support for RabbitMQ, … -
Django - How to logging by decorator?
I want to set up logging for every single API function by using decorator for simplicity. But keep encountering the same error. Please help settings.py log_dir = './log' #create a folder for logging log_dir = os.path.abspath(log_dir) if log_dir and not os.path.exists(log_dir): os.mkdir(log_dir) LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'short': { #for internal errors 'format': '%(asctime)s.%(msecs)03d|%(levelname)s|%(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, 'data': { #for error relate to db 'format': '%(asctime)s.%(msecs)03d|%(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'file_fatal': { #folder for db errors 'level': 'CRITICAL', 'class': 'logging.FileHandler', 'filename': os.path.join(log_dir, 'fatal.log').replace('\\', '/'), 'formatter': 'data', }, 'file_info': { #folder for internal errors 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': os.path.join(log_dir, 'info.log').replace('\\', '/'), 'formatter': 'short', }, }, 'loggers': { 'main': { 'handlers': ['file_info'], 'level': 'DEBUG', 'propagate': True, }, } } This is my views.py def func_detail(func): #function for the decorator @wraps(func) def func_wrapper(requests,*args, **kwargs): log = logging.getLogger('main') try: response = func(requests, *args, **kwargs) except: log.debug('Exception', func.__name__) class simple_function(generics.GenericAPIView): @func_detail def get(self,requests): input_1 = requests.GET.get('input_1') input_2 = requests.GET.get('input_2') input_3 = requests.GET.get('input_3') return JsonResponse([{'aaa':111, 'bbb':222, 'ccc':333}],safe =False) Got this error when running it: TypeError at /simple_function 'NoneType' object is not callable When I comment out the decorator @func_detail, it works normally -
'Incorrect Padding' error while using google.oauth2 id_token.verify_oauth2_token() in Django
I am trying to verify a user's submitted google authentication JWT from a React frontend to my Django backend. I have my frontend POST a request to the backend with the JWT, and then my backend extracts it from the request and processes it through google's recommend token authentication found here. My problem is that each time I process a JWT received from my frontend through id_token.verify_ouath2_token(), an error about 'incorrect padding' is raised ultimately stemming from the base64 encoding of the token. When testing this manually by copy-pasting the token I have extracted from the POST request, however, it works perfectly fine and does not raise an error. So somewhere in my handling of the post request something goes wrong, but I'm not sure what. I have tried decoding the POST request in utf-8 and ascii, and simply leaving the JWT in the bytes form that I extracted it as. All of these throw the same error, and I'm left pretty confused. Here is my code: views.py def login(request): if request.method == "POST": print(request.body.decode("ascii")) # For decoding. By copy/pasting this output into id_token.verify_oauth2_token instead of the token variable, the function returns successfully try: token = request.body.decode("ascii") # Specify the … -
Assigning Value(s) to ManyToMany Field
I'm trying to assign a value onto a ManyToMany field in the Order class. def assign_order(request, user_id): order_id = request.session.get('order_id') #picking this session from a previous fxn allowing me to call the order.id order = get_object_or_404(Order, id=order_id) employee = Employee.objects.filter(user_id=user_id) #Employee is a profile model leveraging an AbstractUser order.deliverer.set(employee) #using .set() for direct assignment of user(Employee) onto ManyToMany field on "Order" order.status = 'deliverer_assigned' order.save() The problem with this schema is that the fxn will always overwrite my ManyToMany field rather than append a new User(Employee profile) onto it. 1. Is there a better way of accomplishing what I need? i.e. Updating a ManyToMany field outside the admin? 2. How do I prevent the overwrite problem in this scenario? -
unable to import rest_framework_simplejwt
I have installed djangorestframework-simplejwt package and trying to import that module in urls.py and views.py but still its not working .Please guide me to solve this issue.. pip list ''' Package Version ----------------------------- ------- asgiref 3.3.1 Django 3.1.4 djangorestframework 3.12.2 djangorestframework-simplejwt 4.6.0 pip 20.2.3 PyJWT 1.7.1 pytz 2020.4 setuptools 49.2.1 sqlparse 0.4.1 Settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Django_MedicalApp', 'rest_framework', 'rest_framework_simplejwt',] REST_FRAMEWORK = {'DEFAULT_AUTHENTICATION_CLASSES': ['rest_framework_simplejwt.authentication.JWTAuthentication',], 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.AllowAny','rest_framework.permissions.IsAuthenticatedOrReadOnly',)} urls.py from rest_framework_simplejwt.views import TokenObtainPairView router = routers.DefaultRouter() router.register('Company',views.CompanyViewset,basename='Company') urlpatterns = [ path('admin/', admin.site.urls), path('api/',include(router.urls), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'))] views.py from rest_framework_simplejwt.authentication import JWTAuthentication class CompanyViewset(viewsets.ViewSet): authentication_classes = [JWTAuthentication] ''' please help me to resolve this import error -
I am having urls.py patterns errors
from django.urls import path from django.urls import include from . import views urlpatterns=[ path("",views.index,name="index") ] i have views.py as follows from django.shortcuts import render from . models import ClientServiceRepresentative # Create your views here. def index(request): return render(request,"ClientServicesManagement/index.html",{"representatives":ClientServiceRepresentative.objects.all()}) When I run the application i get following error File "C:\Users\hp\KHSystem\KHSystems\ClientServicesManagement\urls.py", line 6, in <module> path("",views.index,name="index") AttributeError: module 'ClientServicesManagement.views' has no attribute 'index' I have clearly defined index in views why i am having this problem -
Django Static files not found - Site works but not pulling through static files - 404 console message
I am receiving a 404 for my static files, pages load but when inspect the console it relays the following errors, i've been sratching my head for while on this one. Would someone be able to point me in the right direction, it would be massively appreciated!: 127.0.0.1/:10 GET http://127.0.0.1:8000/static/css/all.css net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:12 GET http://127.0.0.1:8000/static/css/bootstrap.css net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:14 GET http://127.0.0.1:8000/static/css/style.css net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:16 GET http://127.0.0.1:8000/static/css/lightbox.min.css net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:26 GET http://127.0.0.1:8000/static/js/jquery-3.3.1.min.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:28 GET http://127.0.0.1:8000/static/js/lightbox.min.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:27 GET http://127.0.0.1:8000/static/js/bootstrap.bundle.min.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:29 GET http://127.0.0.1:8000/static/js/main.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:28 GET http://127.0.0.1:8000/static/js/lightbox.min.js net::ERR_ABORTED 404 (Not Found) 127.0.0.1/:29 GET http://127.0.0.1:8000/static/js/main.js net::ERR_ABORTED 404 (Not Found) Here's some of the code from the settings.py file: DEBUG = True TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] STATIC_ROOT= os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIR =[ os.path.join(BASE_DIR, '/btre/static/') ] Here's the base.html file: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Font Awesome --> <link rel="stylesheet" href="{% static 'css/all.css' %}"> <!-- Bootstrap --> <link rel="stylesheet" href="{% static 'css/bootstrap.css' …