Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot understand django user group change signal behavior
I have a function to receive a signal when users change their group. @receiver(signal=m2m_changed, sender=User.groups.through) def save_profile(instance, action, reverse, model, pk_set, using, *args, **kwargs): print(model, instance) When I change the group of the user with username "test" using the superadmin interface it outputs <class 'django.contrib.auth.models.Group'> test. But when I do it using following code, group = Group.objects.get(name='Customer') group.user_set.add(user) user.save() it outputs <class 'django.contrib.auth.models.User'> Customer. Because of the above issue I cant use if instance.groups.filter(name='Customer').exists(): #Do something inside the save_profile funtion. When I change groups using second method it gives AttributeError at /register/ 'Group' object has no attribute 'groups' error. How can I avoid getting this error? -
"DJANGO_SETTINGS_MODULE" bash: syntax error near unexpected token
I wonder why I get this error : django.core.exceptions.ImproperlyConfigured: Passing a 3-tuple to include() is not supported. Pass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument to include() instead. (.venv) this is my code : $ python manage.py runserver 9999 then I tried $ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") however it turns out: bash: syntax error near unexpected token `"DJANGO_SETTINGS_MODULE",' (.venv) -
how to using cookies to get data from local storage - DJANGO
i was new in django. i want to get my data back from local storage, but i don't know how to get it. can someone explain me? my application using form NOT MODELS. the application made using django, i use FileField to get files and pass it to local storage. i was hear to get data, i can use cookies, since client data at local storage can't be get. from django import forms class Audio_store(forms.Form): password=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control', 'text-align' : 'center;'})) audio=forms.FileField(widget=forms.FileInput(attrs={'style': 'width: 300px;', 'class': 'form-control', 'text-align' : 'center;'})) -
Restrict view on utils.py - Django
I've used a tempalte to create a calendar using Django, but now i'm stuck to limit the view of the events on this calendar to just the user who have created the event. I have no model for this calendar, just for the events, and the calendar is currently based on my util.py file: utils.py class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): contracts_starting_per_day = events.filter(starting_date__day=day) contracts_ending_per_day = events.filter(ending_date__day=day) contracts_paying_per_day = events.filter(payment_date__day=day) d = '' for contract in contracts_starting_per_day: if contract.company_client: client = contract.company_client elif contract.person_client: client = contract.person_client else: client = '-' d += f"<a href='http://127.0.0.1:8000/contracts/editct/{contract.id}'> <li class='calendar-li starting' title='{contract.contract_name}'> {contract.contract_name} <p class='calendar-p'> {client} </p> </li> </a>" if day != 0: return f"<td class='calendar-td'><span class='date'>{day}</span><ul class='calendar-ul'> {d} </ul></td>" return "<td class='calendar-td'></td>" # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f"<tr class='calendar-tr'> {week} </tr>" # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True): contracts = Contract.objects.filter(starting_date__year=self.year, starting_date__month=self.month) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' … -
Form data is passing in html table
I am submitting the form data by using fetch API and then I want to show some variable values in HTML table. But it's not working as it's supposed to be. I am able to fetch the form data in views.py but I am not able to send it back to the HTML file to show the same data on a table. Without the fetch API submit, everything is working fine as per my need. I can't get what my mistake is. I have tried to remove all unnecessary parts to debug. Please let me know where I am going wrong. views.py def home(request): context={} if request.method=="POST": options_value=request.POST['dropdown_val'] value=request.POST['val'] print(options_value,value) context={"options_value":options_value, "value":value} return render(request, 'index.html',context) index.html <form method="POST" action="" id="form"> {% csrf_token %} <select class="form-select" aria-label="Default select example" name="options_value" id="dropdown_val" > <option disabled hidden selected>---Select---</option> <option value="1">Profile UID</option> <option value="2">Employee ID</option> <option value="3">Email ID</option> <option value="4">LAN ID</option> </select> <input type="text" class="form-control" type="text" placeholder="Enter Value" name="value" id="value" /> <input class="btn btn-primary" type="submit" value="Submit" style="background-color: #3a0ca3" /> </form> <table style="display: table" id="table"> <tbody> <tr> <th scope="row">ProfileUID :</th> <td>{{options_value}}</td> </tr> <tr> <th scope="row">First Nane :</th> <td>{{value}}</td> </tr> </tbody> </table> <script> let form = document.getElementById("form"); let dropdown_val = document.getElementById("dropdown_val"); let val = document.getElementById("value"); const … -
How to retrieve data based on specific field in Django Rest Framework using RetrieveAPIView?
With the code below, I am able to retrieve data based on id, how can I update this code so I can retrieve data based on fileName instead? My urls is urlpatterns = [ path("items/<pk>", SingleUploadItem.as_view()), ] My views is: class SingleUploadItem(RetrieveAPIView): queryset = fileUpload.objects.all() serializer_class = fileUploadSerializer My model is class fileUpload(models.Model): fileName = models.CharField(max_length=200, unique=True, blank=True) -
Django comments deletion
I am having challenges in getting user comment deletion functionality for my django blog. The logic is as follows: user who made a comment under blog post and is logged in will see Delete button next to their comment once the user click on delete comment button they are taken to Comment_confirm_delete page to confirm deletion Below is what I have: Models.py from django.db import models from django.contrib.auth.models import User from cloudinary.models import CloudinaryField STATUS = ((0, "Draft"), (1, "Published")) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts") updated_on = models.DateTimeField(auto_now=True) content = models.TextField() featured_image = CloudinaryField('image', default='placeholder') excerpt = models.TextField(blank=True) created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) likes = models.ManyToManyField(User, related_name='blog_likes', blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=80) body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) class Meta: ordering = ['-created_on'] def __str__(self): return f"Comment {self.body} by {self.name}" def get_absolute_url(self): return reverse('post-detail', kwargs={'comment': id}) urls.py from . import views from .views import CommentDeleteView from django.urls import path urlpatterns = [ path("", views.PostList.as_view(), name="home"), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), path('like/<slug:slug>', views.PostLike.as_view(), name='post_like'), path('delete/<comment_id>', views.CommentDeleteView.as_view(), name='comment_confirm_delete') ] views.py … -
Change boolean data when adding new registration
in this code i want change a boolean data of room when adding new registration For example: when i add new registration in django admin the boolean data of room change to False please can u help in it from django.db import models from django.contrib.auth.models import User class Rooms(models.Model): room_num = models.IntegerField() room_bool = models.BooleanField(default=True) category = models.CharField(max_length=150) def __str__(self): return f'{self.room_num}' class Meta: verbose_name = 'Room' class Registration(models.Model): rooms = models.ForeignKey(Rooms, on_delete=models.CASCADE) first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) admin = models.ForeignKey(User, on_delete=models.CASCADE) pasport_serial_num = models.CharField(max_length=100) birth_date = models.DateField() img = models.FileField() visit_date = models.DateTimeField() leave_date = models.DateTimeField() guest_count = models.IntegerField() def func(self): room = Rooms.objects.filter(room_bool=True) for i in room: if i.room_num == int(self.rooms): i.room_bool = False #this should change when adding new registration i.save() -
How to let Kombu consumer return or stream queued message
I am using Kombu and RabbitMq to queue the JPEG image data and stream or return the dequeued message back so it shows the video streaming on the webpage. Kombu consumer detects the message sent from the producer declared in detection.py file, but it does not save or return any message back so basically nothing is showing on the web. I read Kombu documentation but still I have trouble understanding the problem of my code. Any help would be greatly appreciated.. color_detection.py: The following code declares Kombu producer and publish the message to the exchange called video-exchange. from kombu import Connection from kombu import Exchange from kombu import Producer from kombu import Queue import numpy as np import cv2 import sys # Default RabbitMQ server URI rabbit_url = 'amqp://guest:guest@localhost:5672//' # Kombu Connection conn = Connection(rabbit_url) channel = conn.channel() # Kombu Exchange # - set delivery_mode to transient to prevent disk writes for faster delivery exchange = Exchange("video-exchange", type="direct", delivery_mode=1) # Kombu Producer producer = Producer(exchange=exchange, channel=channel, routing_key="video") # Kombu Queue queue = Queue(name="video-queue", exchange=exchange, routing_key="video") queue.maybe_bind(conn) queue.declare() ''' ML object detection algo(haarcascade)used to identify objects. the XML file consists of trained Haar Cascade models. ''' face_cascade = cv2.CascadeClassifier( 'accounts/personal_color/self_detection/haarcascade_frontalface_default.xml') # … -
Is there a way to display all user last_login and date_joined in django
I want to display all users information on admin dashboard with their last_login and join date I filter user date to display on template data = Profile.objects.filter(Q(user__is_superuser=False), Q(user__is_staff=False)).order_by('-user__last_login')[:10] Profile model user = models.OneToOneField(User,default="1", on_delete=models.CASCADE, related_name="profile") image = models.ImageField(upload_to="images",default="default/user.png") def __str__(self): return f'{self.user} profile' I want to do like -
I am gettitng post method not allowed
from rest_framework.decorators import api_view @api_view(['GET', 'POST']) def contact(request): if request.method == 'GET': contact = ContactMe.objects.all() serializer = ContactMeSerializer(contact, many=True) return JsonResponse(serializer.data, safe=True) elif request.method == 'POST': data = JSONParser().parse(request) serializer = ContactMeSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.data, safe=False) I am getting post method not allowed, i don't know why i keep getting post method not allowed. The source code is below. Thanks from django.urls import path from .views import ListingView, SearchView, ListingsView, contact urlpatterns = [ path('contact/', contact) ] -
showing date from db in html date in django
How can i show date from db in django html template with input type date. As You can see if we use input type 'date'. we can see the below widget showing in html. But if i want to it to show date from DB in below picture. Is there anyway i can do? [![enter image description here][1]][1] Showing like this, so user can see the current date from DB and change if needed. forms.py class ProfileUpdateForm(ModelForm): #birthdate = forms.DateField( # input_formats=['%dd-%mm-%yyyy'], # widget=forms.DateInput(format='%dd-%mm-%yyyy', attrs={'type': "date"}) # ) class Meta: model = User fields = [ 'email', 'full_name', 'address', 'city', 'state', 'postcode', 'phone_number', 'birthdate', ] widgets = { 'full_name': Textarea(attrs={'cols': 35, 'rows': 1}), 'address': Textarea(attrs={'cols': 80, 'rows': 3}), 'city': Textarea(attrs={'cols': 35, 'rows': 1}), 'birthdate': forms.DateInput(format='%d %b %Y', attrs={'type':'date'}), } -
Add template variable into URL and satisfy reverse match
I found a way to inject variables into the URL per Django Template: Add Variable Into URL As Parameter, but my reverse match is not working. Do I need to use re-path and use regular expressions? Current url.py path('student/item/drilldown/<str:type>/<int:num>/',views.StudentBehaviorListView.as_view(),name='student_item_list_drilldown'), Original w/hard-coding: <a href="{%url 'registration:student_item_list_drilldown' type='grade' num=6%}"> With variable injection: <a href="{%url 'registration:student_item_list_drilldown'%}?type=grade&num={{i.grade}}">{{i.grade}}th Grade</a> Error message: NoReverseMatch at /registration/dashboard/ Reverse for 'student_item_list_drilldown' with no arguments not found. 1 pattern(s) tried: ['registration/student/item/drilldown/(?P<type>[^/]+)/(?P<num>[0-9]+)/\\Z'] -
Django Form "'ForwardManyToOneDescriptor' object has no attribute 'all'"
Hey so I'm having quite some problems. In effect trying to add a form to a home-page with options for a user to select based on a DB object. Then once submitted the page will refresh, and the form can be used again. Forms.py rom django import forms from django.forms import ChoiceField, ModelForm, RadioSelect from .models import command_node class command_form(ModelForm): class Meta: model = command_node fields = ( 'host_id', 'current_commands' ) host_id = forms.ModelChoiceField( required=True, queryset=command_node.host_id, widget=forms.Select( attrs={ 'class': 'form-control' }, ) ) current_comamnds = forms.ChoiceField( required=True, attrs={ 'class': 'form-control' }, choices=[ ('Sleep', "Sleep"), ('Open SSH_Tunnel', 'Open SSH_Tunnel'), ('Close SSH_Tunnel', 'Close SSH_Tunnel'), ('Open TCP_Tunnel', 'Open TCP_Tunnel'), ('Close TCP_Tunnel', 'Close TCP_Tunnel'), ('Open Dynamic', 'Open Dynamic'), ('Close Dynamic', 'Close Dynamic'), ('Task', 'Task'), ]) Models.py from tkinter import CASCADE from turtle import update from django.db import models class beacon(models.Model): host_id = models.BigAutoField('Id', primary_key=True) hostname = models.CharField('Hostname', max_length=200) internalIp = models.CharField('Internal-IP', max_length=200) externalIp = models.CharField('External-IP', max_length=200) current_user = models.CharField('Current_User', max_length=200) os = models.CharField('OS', max_length=200) admin = models.CharField('Admin', max_length=200) def __str__(self): return self.hostname class command_node(models.Model): host_id = models.ForeignKey(beacon, on_delete=models.CASCADE) current_commands = models.CharField('current_command', max_length=50, null=True) previous_commands = models.CharField('previous_commands', max_length=2000, null=True) def __str__(self): return str(self.host_id) views.py from django.shortcuts import render from django.http import HttpResponse from .models import … -
How to compare model fields using Django-filter package
I am trying to compare two model fields ma8, ma21 using Django-filter but I am not sure where to start. I think I should use F objects like in this answer: How to create a Django queryset filter comparing two date fields in the same model Below is my filters.py file from .models import TheModel from .tables import The TableTable import django_filters class MyFilter(django_filters.FilterSet): ma8__lt = django_filters.NumberFilter(field_name='ma8', lookup_expr='lt') ma8__gt = django_filters.NumberFilter(field_name='ma8', lookup_expr='gt') ma21__lt = django_filters.NumberFilter(field_name='ma21', lookup_expr='lt') ma21__gt = django_filters.NumberFilter(field_name='ma21', lookup_expr='gt') activeYN = django_filters.BooleanFilter(field_name='activeYN') # Here I want to be able to compare two model fields ma8, ma21 ex. ma8 > ma21 class Meta: model = TableData table_class = TableTable fields = ['ma8','ma21','activeYN'] -
Provide initial data for Django models from txt file
I have a .txt file with 3 columns (longitude, latitude, distance) and 40 million rows. These are the first lines of the file. -179.98 89.98 712.935 -179.94 89.98 712.934 -179.9 89.98 712.933 -179.86 89.98 712.932 -179.82 89.98 712.932 -179.78 89.98 712.931 -179.74 89.98 712.93 -179.7 89.98 712.929 -179.66 89.98 712.928 -179.62 89.98 712.927 Is there a way to provide these 40 million rows as initial data to this Django model? from django.db import models class Location(models.Model): longitude = models.FloatField() latitude = models.FloatField() distance = models.FloatField() -
How to annotate a QuerySet with the result of another QuerySet that uses a field of the first?
I'm currently working on the django backend of an app that allows users to place camera markers, each containing multiple cameras. The models I'm working with: class CameraMarkers(models.Model): # Field name made lowercase. marker_id = models.AutoField(db_column='Marker_ID', primary_key=True) # Field name made lowercase. city = models.CharField(db_column='City', max_length=25) # Field name made lowercase. num_of_cams = models.IntegerField(db_column='Num_of_Cams') # Field name made lowercase. zipcode = models.CharField( db_column='Zipcode', max_length=6, blank=True, null=True) # Field name made lowercase. street = models.CharField( db_column='Street', max_length=50, blank=True, null=True) # Field name made lowercase. house_num = models.CharField( db_column='House_num', max_length=10, blank=True, null=True) # Field name made lowercase. company = models.CharField( db_column='Company', max_length=12, blank=True, null=True) # Field name made lowercase. contact_name = models.CharField( db_column='Contact_name', max_length=50, blank=True, null=True) # Field name made lowercase. email_address = models.CharField( db_column='Email_address', max_length=50, blank=True, null=True) # Field name made lowercase. phone_num = models.CharField( db_column='Phone_num', max_length=15, blank=True, null=True) # Field name made lowercase. date_of_visit = models.CharField( db_column='Date_of_visit', max_length=10, blank=True, null=True) class Meta: managed = False db_table = 'Camera Markers' class Cameras(models.Model): # Field name made lowercase. camera_id = models.AutoField(db_column='Camera_ID', primary_key=True) # Field name made lowercase. status = models.CharField(db_column='Status', max_length=20) # Field name made lowercase. view = models.TextField(db_column='View', blank=True, null=True) # Field name made lowercase. marker = models.ForeignKey( CameraMarkers, models.DO_NOTHING, db_column='Marker_ID') … -
Noreversematch: "url-name" not found a valid function or pattern name
I built a simple app to register and login users. Whenever a user registers, redirect to login, when login is successful, redirect to another page. But I get this error, reverse for "url-name" not found. "Url-name" is not a valid view function or pattern name. From the browser traceback it highlighted this code for me 47. return redirect ("videos") Local vars Below is the code. from django.urls import path from .views import Display_all,Registration_view,Login_view,logout_view,index_view urlpatterns = [ path('videos/', Display_all, name ="video"), path('register/',Registration_view, name ='registration'), path('login/', Login_view, name = "login"), path('logout/', logout_view, name = "logout") The views from django.http import HttpRequest, HttpResponse from django.shortcuts import redirect, render from django.views import View from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from .forms import RegistrationForm from django.contrib.auth import authenticate,login, logout from .models import Video def Display_all(request): all_videos = Video.objects.all() context = {"all_videos":all_videos} return render(request, 'videos/displayall.html', context) def Registration_view(request): form = RegistrationForm(request.POST or None) if form.is_valid(): form.save() return redirect("login") else: form = RegistrationForm() context = {"form":form} return render(request, 'profiles/registration.html', context) def Login_view(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request,username=username,password=password) if user is not None: login(request,user) return redirect ("videos") return render(request, 'profiles/login.html',{}) The simple login template <!DOCTYPE html> <html lang="en"> … -
ERROR: Invalid requirement: 'asgiref 3.5.2'
I am new to heroku and I wanted to deploy a simple app, when i push to heroku it is given me the error below. I check online unfortunately I dont find the right answer to it. ERROR GIVEN Enumerating objects: 73, done. Counting objects: 100% (73/73), done. Delta compression using up to 4 threads Compressing objects: 100% (71/71), done. Writing objects: 100% (73/73), 24.58 KiB | 719.00 KiB/s, done. Total 73 (delta 11), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> No Python version was specified. Using the buildpack default: python-3.10.4 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.10.4 remote: -----> Installing pip 22.0.4, setuptools 60.10.0 and wheel 0.37.1 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: ERROR: Invalid requirement: 'asgiref 3.5.2' (from line 1 of /tmp/build_44a6c2b3/requirements.txt) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to olakaymytodo. remote: To https://git.heroku.com/olakaymytodo.git ! [remote rejected] main -> main (pre-receive … -
how to Serialize multiple objects in Django
I have 2 models for admin and member positions and I would like to get both of the models in one API call to fetch the data on my front end. I tried to do many things so can some one help me :( class ClinetAdminPosition(models.Model): name = models.CharField(max_length=128, null=True) company = models.ForeignKey( to="Company", on_delete=models.CASCADE, related_name="admin_positions", null=True ) modified_at = models.DateTimeField(verbose_name="Updated", auto_now=True, editable=True) created_at = models.DateTimeField(verbose_name="Created", auto_now_add=True, editable=False) def __str__(self): return f"{self.name}" class ClinetMangerPosition(models.Model): name = models.CharField(max_length=128, null=True) company = models.ForeignKey( to="Company", on_delete=models.CASCADE, related_name="manger_positions", null=True ) modified_at = models.DateTimeField(verbose_name="Updated", auto_now=True, editable=True) created_at = models.DateTimeField(verbose_name="Created", auto_now_add=True, editable=False) def __str__(self): return f"{self.name}" I want to get both models' data from 1 API request to be like this: [ { "admin_positions": [ { "name": "test", "company": 1 }, { "name": "test2", "company": 1 }, { "name": "test3", "company": 1 } ], "manger_position": [ { "name": "test", "company": 1 }, { "name": "test2", "company": 1 }, { "name": "test3", "company": 1 } ] } ] -
Django CSRF not working on SSL(HTTPS), but working on local(linux), tried all things
Following is the Error i get : 403 : CSRF verification failed. Request aborted. When Debug = True : Reason given for failure: Origin checking failed - https://example.com does not match any trusted origins. Basic Checks : site is having valid working ssl browser is accepting cookie for this site In settings.py "CSRF_COOKIE_SECURE = True" is set In settings.py "django.middleware.csrf.CsrfViewMiddleware" is above other View Middleware I have tried many things, nothing works. It works perfectly on development environment -
How do I destructure an API with python Django and django-rest-framework?
I have a successfully compiled and run a django rest consuming cocktaildb api. On local server when I run http://127.0.0.1:8000/api/ I get { "ingredients": "http://127.0.0.1:8000/api/ingredients/", "drinks": "http://127.0.0.1:8000/api/drinks/", "feeling-lucky": "http://127.0.0.1:8000/api/feeling-lucky/" } but when I go to one of the links mentioned in the json result above, for example, http://127.0.0.1:8000/api/ingredients/ I get an empty [] with a status 200OK! I am learning and I would appreciate any tips on where I should focus on. Thanks in advance. -
filter Boto3 s3 file filter does not find file
I am trying to check if a file exists in boto3 with django before adding it to the django model session = boto3.Session( aws_access_key_id=env("AWS_ACCESS_KEY_ID"), aws_secret_access_key=env("AWS_SECRET_ACCESS_KEY"), ) s3 = session.resource( "s3", region_name=env("AWS_S3_REGION_NAME"), endpoint_url=env("AWS_S3_ENDPOINT_URL") ) bucket = s3.Bucket(env("AWS_STORAGE_BUCKET_NAME")) Then when I try to search the file: objs = list(bucket.objects.filter(Prefix="media/" + name)) It shows that it could not find the file with according to the name passed. Although when I do bucket.objects.all(), I find the file existing under media/NAME_HERE -
When I use Bootstrap to build a web apps by python but it didn't show me the correct page
enter image description here enter image description herecom/KF5ap.png -
template rendering works fine but when I use template inheritance it displays error
I tried the using {% include 'navbar.html'%} on room.html template both of them work fine and display the template but when I add {% include 'navbar.html'%} in room.html try to render it displays this error I adjust have also include the templates in the setting what seems to be the problem. The urls file in first app is from django.urls import path from . import views urlpatterns =[ path('',views.home), path('room/',views.room), path('navbar/',views.navbar), and the views file is like this from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request,'firstapp/home.html') def room(request): return render(request,'firstapp/room.html') def navbar(request): return render(request,'firstapp/navbar.html') def main(request): return render(request,'main.html') images of error displayed in Django and setting file [1]: https://i.stack.imgur.com/MH8fL.png error displayed in Django [2]: https://i.stack.imgur.com/Wh8Ot.png error displayed in Django [3]: https://i.stack.imgur.com/phUt0.png settings file