Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        Django Rest Framework Serializer - return related fieldI have a model with a one-to-one relationship with a main model: class User(models.Model): id = models.BigIntegerField(primary_key=True) username = models.CharField(max_length=100, blank=True) class AggregatedStats(models.Model): user_id = models.ForeignKey('User', on_delete=models.DO_NOTHING, unique=True) followers_30d = models.BigIntegerField(blank=True) I have written the following serializers: class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['id', 'username', 'followers'] class AggregatedStatsSerializer(serializers.HyperlinkedModelSerializer): username = UserSerializer(source='user.username') class Meta: model = AggregatedStats fields = ['followers_30d', 'username'] I am trying to return the username from the User model, but whatever I try to get it, the best I can do is get the hyperlinked related field from user, but not the actual "username" attribute. How would you return this?
- 
        How to add different default values to Foreign Key in Django Models?I have two models (Article and ArticleContent), in Article, three instances of ArticleContent, which should change only one attribute.I am doing this because each article will have its respective translation. These are my models: class ArticleContent(models.Model): class LANGUAGES(models.TextChoices): ES = 'es', 'Español' EN = 'en', 'English' PT = 'pt', 'Português' language = models.CharField(choices=LANGUAGES.choices, max_length=2) title = models.CharField(max_length=300) body = models.TextField() class Article(models.Model): content_es = models.ForeignKey(ArticleContent, on_delete=models.CASCADE, related_name='article_es') content_en = models.ForeignKey(ArticleContent, on_delete=models.CASCADE, related_name='article_en') content_pt = models.ForeignKey(ArticleContent, on_delete=models.CASCADE, related_name='article_pt') cover_image = models.FileField(upload_to='uploads/') chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE, related_name='articles') What I need to do is something like this, in my Article model: content_es = models.ForeignKey(ArticleContent(language=ArticleContent.LANGUAGES.ES), on_delete=models.CASCADE, related_name='article_es') content_en = models.ForeignKey(ArticleContent(language=ArticleContent.LANGUAGES.EN), on_delete=models.CASCADE, related_name='article_en') If I could do it this way, I could define a default value according to the language. Is there any way to do this?
- 
        It's possible to set the m2m field without saving it in the database/create a database connection/query in Django?I want to use bulk method to update m2m field, but not works, because .add and .set method create a database connection. These methods take a long time to execute, and the objective of the bulk is precisely to make the insertion be in bulk, and not one at a time Code sample: athletes = Athlete.objects.all() games = Game.objects.all() # objects to update in bulk games_objs_with_m2m = [] for game in games: athlete_related = athletes.get(id=game.athlete_id_ref) game.athlete.add(athlete_related) # here is the problem, .add or .set create a db connection for each instance games_objs_with_m2m.append(game) Game.objects.bulk_update(games_objs_with_m2m, ["athlete"]) Complete code, a script to populate data from csv file: https://pastebin.com/L1pMzBU4
- 
        Django mobile usersI am currently developing a full-stack solution(web & mobile) using Django restful API as a backend service, my question is how to prevent mobile users from connecting to the web dashboard ?? should I use different endpoints for the mobile version and handle permissions from there ?? what is the best approach you suggest thank you!
- 
        Adding a background task to DjangoI don't know if i've chosen a good approach to the problem I'm facing. In fact, there's a very high chance that I'm completely wrong about this. In my Django Application, I need to establish a connection with Twitter API, to continuously get desired tweets. In order to do so, I've written a script using def connect(): response = requests.get( "https://api.twitter.com/2/tweets/search/stream", headers=headers, stream=True, ) for response_line in response.iter_lines(): if response_line: json_response = json.loads(response_line) print(json.dumps(json_response, indent=4, sort_keys=True)) The problem is, I don't know how and where to call this function in Django. Here's what I've found so far: This function blocks the flow of its caller, So it needs to be executed concurrently, whether as a process or a thread. In order to execute such a function, also known as a background task, I need to either use heavy complex options, such as Celery, or light-weight libraries such as DjangoBackgroundTasks. Obviously, I went with DjangoBackgroundTasks and installed it. But now there are a few problems that I can't solve. Firstly, where in the code should I call my connect() function? I've seen people call this in console, but that's not what I want to do, I need to call this, and …
- 
        How can I place two inputs side by side>I am working with Django Forms and I want to place two input fields side by side but don't have a wrapper on them so is there any way I can do that through css?
- 
        Django Form: copy CheckboxSelectMultiple behavior into a (multi) selectable icon gallery to build a nice menuHi I'm trying to achieve this kind of menu design (see image bellow) Basically, the "1" tooltiped image should show a selected state when clicked (like sourrounded)... There will be more images in this row (less than 5) in the future, and they will all have to be selectable (multiple selections), so the underlying form can update everytime a selection is changed This will change the collection of "species" images bellow based on selected categories... So this is exactly the same behavior than a CheckboxSelectMultiple but without the checkbox, ul/li etc, just the icon and "checked" or not state visible... the model: class SpeciesCat(models.Model): category = models.CharField(max_length=255, unique=True, null=False) logo = models.ImageField(blank=True, null=True) def __str__(self): return (self.category) class Meta: ordering = ['category'] class Species(models.Model): category = models.ForeignKey(to=SpeciesCat, null=False, on_delete=models.DO_NOTHING) common_name = models.CharField(max_length=255, unique=True, null=False) logo = models.ImageField(blank=True, null=True) def __str__(self): return (self.common_name) class Meta: ordering = ['common_name'] the form: class CategoriesSelectForm(forms.Form): categories = forms.ModelMultipleChoiceField(queryset=SpeciesCat.objects.all(), widget=forms.SelectMultiple(attrs={"onchange": "this.form.submit()"}), required=False) the view: def index_view(request): species = [] if request.method == "POST": if "categories" in request.POST: if categories_form.is_valid(): categories = categories_form.cleaned_data["categories"] species = Species.objects.filter(category__in=categories) context = {'species_list': species} return render(request, 'home/home.html', context) the template: <div id="left_menu_floatbar"> <div class="menu_row"> <form name="categories" action="/" method="post">{% csrf_token %} …
- 
        Django - request.is_secure always returns FalseI'm running a Django project on a DigitalOcean VPS using Nginx and Gunicorn. I made sure that i'm using HTTPS, but for some reason using request.is_secure() always returns False, and request.scheme returns HTTP, even though i made sure it's VPS. What could be the reason for that? Here is my nginx config: server { listen 80; server_name MY.SERVER.com; location / { include proxy_params; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/var/www/proj/myproj.sock; } } And i also made sure to add to my Django settings SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https'). Any advice is appreciated
- 
        How to add Trailing slash (/) in url of sitemap Django?I want to add (/) in site map of Django. I have used following code to generate sitemap in django my url.py is from django.contrib.sitemaps.views import sitemap from myApp.sitemaps import staticSitemap , mySitemap sitemaps = { 'staticSitemap':staticSitemap, 'mySitemap':mySitemap } urlpatterns = [ path('admin/', admin.site.urls), path('sitemap.xml', sitemap, {'sitemaps': sitemaps} ), path('<slug:slug>/',apps.switcher, name='calc_detail'), ] my sitemap file is like below from django.contrib.sitemaps import Sitemap from django.shortcuts import reverse from .models import SingleCalculator class staticSitemap(Sitemap): changefreq = "weekly" priority = 0.9 def items(self): return ['home','about','contact','privacy'] def location(self, item): return reverse(item) class mySitemap(Sitemap): changefreq = "weekly" priority = 0.7 def items(self): return SingleCalculator.objects.all() def lastmod(self,obj): return obj.lastmod Sitemap is generating now like following URL in loc <loc>https://sitename.com/absolute-difference-calculator</loc> I want (/) after the end of url. How can I do this?
- 
        Django custom authentication with a mysql dbIm using Django without models and an external authentication source (mysql db). Im searching now for a way to authenticate and login users with that mysql db. It should also be possible to use user.is_authenticated in templates. Im not sure if that's only possible if I replicate the mysql db to Django's Usersmodels. But I think that would be hard to maintain. Like updating both on a passwordreset and so on. In a nutshell: Is there a way to authenticate Users in Django externally, and have the advantage of user.is_authenticated and @login_required.
- 
        Django Comment Section Issueim new to django , im trying to build a blog by my self but i sucked on comment section 1- i dont know to make comment form under the blog post without going to a new page using Class Based View 2- i could add comment section and the logic that i need using function view but im facing a problem . when i try to post a comment with a user it says You are trying to change the nullable field 'name' on comment to non-nullable without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Ignore for now, and let me handle existing rows with NULL myself (e.g. because you added a RunPython or RunSQL operation to handle NULL values in a previous data migration) Quit, and let me add a default in models.py if i put null=True on name model it will show the comment without the author class Comment(models.Model): post = models.ForeignKey(Postrelated_name='comments', on_delete=models.CASCADE) name = models.ForeignKey(User, related_name='author', on_delete=models.CASCADE) comment = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return …
- 
        how to get id of an object from url of page djangoi have created a list in which it shows the name of all groups present when you click it redirect to another page with group id, when i create a post i need to specify which group it is, i am getting the id in url of page but i have no idea how to define group object with that url, views def create(request): if request.method == "POST": name = request.user author = request.user message = request.POST['message'] message = comments(user=author,message=message,name=name,group_id=2) message.save() return HttpResponse('') instead of group_id=2 or hardcode it , can i automatically take the id from url of the page like we do in request.user models class group(models.Model): group_name = models.CharField(max_length=100) group_user = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return f'{self.id} group' class comments(models.Model): userId = models.AutoField(primary_key=True) name = models.CharField(max_length=100) group = models.ForeignKey(group,on_delete=models.CASCADE,null=True) user = models.ForeignKey(User,on_delete=models.CASCADE) message = models.TextField() date = models.TimeField(auto_now_add=True) def __str__(self): return f'{self.user} comments' i have been trying day and night and couldnt solve, all the genius programmers out there pls give me a solution
- 
        How can I download CSV file from the URL and use that data in my own backend? (Node.js or Python)I have link which when I open in the browser it downloads the CSV file with the data. How can I use a backend controller that will open that link and use that downloaded CSV for fetching that data? I am planning to make it either with Node.js or Python
- 
        How to limit top N of each group in Django ORM by using Postgres Window functions or Lateral Joins?I have following Post, Category & PostScore Model. class Post(models.Model): category = models.ForeignKey('Category', on_delete=models.SET_NULL, related_name='category_posts', limit_choices_to={'parent_category': None}, blank=True, null=True) status = models.CharField(max_length=100, choices=STATUS_CHOICES, default='draft') deleted_at = models.DateTimeField(null=True, blank=True) ... ... class Category(models.Model): title = models.CharField(max_length=100) parent_category = models.ForeignKey('self', on_delete=models.SET_NULL, related_name='sub_categories', null=True, blank=True, limit_choices_to={'parent_category': None}) ... ... class PostScore(models.Model): post = models.OneToOneField(Post, on_delete=models.CASCADE, related_name='post_score') total_score = models.DecimalField(max_digits=8, decimal_places=5, default=0) ... ... So what i want is to write a query which returns N number of posts (Posts) of each distinct category (Category) sorted by post score (denoted by total_score column in PostScore model) in descending manner. So that i have atmost N records of each category with highest post score. So i can achieve the above mentioned thing by the following raw query which gives me top 10 posts having highest score of each category : SELECT * FROM ( SELECT *, RANK() OVER (PARTITION BY "post"."category_id" ORDER BY "postscore"."total_score" DESC) AS "rank" FROM "post" LEFT OUTER JOIN "postscore" ON ("post"."id" = "postscore"."post_id") WHERE ("post"."deleted_at" IS NULL AND "post"."status" = 'accepted') ORDER BY "postscore"."total_score" DESC ) final_posts WHERE rank <= 10 What i have achieved so far using Django ORM: >>> from django.db.models.expressions import Window >>> from django.db.models.functions import Rank >>> …
- 
        Forms Django PythonCould someone help me? I don't know what I'm doing wrong. I try to change ma value in database but it doesn't work. Still it is the same like it set default.. Below my codes...Thank You in advance. koszyk.html {% for produkt in produkty%} <div id="bin"> <div class ='name'>{{ produkt.nazwa }}</div> <div class="product_price"> {{ produkt.cena }} {{ produkt.ilosc }} <form method="POST"> {% csrf_token %} {{ form }} <button type="submit" href ="{% url 'numbers' produkt.id %}">zaktualizuj</button> </form> </div> <div class="delete"> <a href="{% url 'usun' produkt.id %}">Usuń</a></div> {% endfor %} models.py class Basket(models.Model): nazwa = models.CharField(max_length=64, blank=False, unique=True, default="") cena = models.PositiveSmallIntegerField(default=2000) opis = models.TextField(default="") ilosc = models.PositiveSmallIntegerField(default=3) forms.py from django.forms import ModelForm from .models import Shop, Basket class IloscForm(ModelForm): class Meta: model = Basket fields = ['ilosc',] views.py def numbers(request, id): form = IloscForm(request.POST or None) produkt = Basket.objects.get(pk=id) if form.is_valid(): ilosc = form.save(commit=False) produkt.ilosc = ilosc ilosc.save() return redirect('koszyk') def koszyk(request): produkty = Basket.objects.all() form = IloscForm() return render(request, 'koszyk.html', {'produkty': produkty, 'form':form}) I would be very grateful for help! Natalia
- 
        How to call a function from models.py to views or templateI am a beginner in Django and Python. I am creating a Payroll project whose calculations are done using a function from models.py. The user must input the variables through templates and save it to sql. Then search for the employee (through templates again) and output his payroll details. That is the time when I want to use the calculation function. Data from the database is working and is outputted by the templates. As for the calculated data, it simply isn't showing. I have been trying to use the function to no avail and I've searched for 3 days already. I am at lost at what to do now. models.py from django.db import models #Class in model.py acts as a table in database class Add_Employee(models.Model): name = models.CharField (max_length = 150, default = '', null = False) position = models.CharField (max_length = 150, default = '', null = False) email = models.EmailField (max_length = 150, default = '', null = False) address = models.CharField (max_length = 500, default = '', null = False) basic_pay = models.FloatField(default=None) overtime_hours = models.IntegerField(default=None) allowance = models.FloatField(default=None) days_leave = models.IntegerField(default=None) other_deductions = models.FloatField(default=None) #Django admin page; the table will show the name def __str__(self): return …
- 
        Can I create a Django object instance using a previous object's value, race-condition-free?TLDR When creating a new object using Django ORM, can I, in a transactionally safe / race-condition-free manner, set a field's value based on an already existing object's value, say F('sequence_number') + 1 where F('sequence_number') refers not to the current object (which does not exist yet) but to any given object in the table? Longer version I have a model Issue with properties sequence_number and sequence_prefix. There is a unique constraint on (sequence_prefix, sequence_number) (e.g. DATA-1). class Issue(models.Model): created_at = models.DateTimeField(auto_now_add=True) sequence_prefix = models.CharField(blank=True, default="", max_length=32) sequence_number = models.IntegerField(null=False) class Meta: constraints = [ models.UniqueConstraint( fields=["sequence_prefix", "sequence_number"], name="unique_sequence" ) ] The idea is that issues —for auditing purposes— have unique sequence numbers for each variable (user-determined) prefix: when creating an issue the user selects a prefix, e.g. REVIEW or DATA, and the sequence number is the incremented value of the previous issue with that same sequence. So it's like an AutoField but dependent on the value of another field for its value. There can not be two issues DATA-1, but REVIEW-1 and DATA-1 and OTHER-1 all may exist at the same time. How can I tell Django when creating an Issue, that it must find the most recent object for …
- 
        django admin - Define instance of formset on dynamic creation of inlinesHere's what I try to achieve: I have a Category and an Author model. To every Category I can save n authors. Category is an MPTT (tree) model. I need to show on the admin detail/change view in the admin a given category, all authors AND all the children-categories AND their authors. I can create the level-2-author-inlines very nicely like this: def get_inline_instances(self, request, obj=None): inline_list = super().get_inline_instances(request, obj) for child_category in self.object_from_request(request).children.all(): inline_list.append( ChildAuthorInline(self.model, self.admin_site, child_category=child_category)) return inline_list My Inline class looks like this: class ChildAuthorInline(admin.TabularInline): """ Dynamically created inline to show authors of child categories. """ model = Author extra = 0 fields = ('name',) def __init__(self, parent_model, admin_site, *, child_category): self.child_category = child_category self.verbose_name_plural = _(f'Category {child_category.name}') super().__init__(parent_model, admin_site) def get_queryset(self, request): return Author.objects.filter(category=self.child_category) So far, so good. The problem is: When I want to add a new author to a child category, the instance of the formset is still the parent category. I tried everything but wasn't able to inject the child category and use it in the original part of the formset. And yes, I could overwrite the template or copy a bunch of django code, but this is too hack for my taste... There …
- 
        django rest connecting with react trough INSTALLED_APPSI'm running trough my m8 project (Django Rest Framework + React) and there is something like this: INSTALLED_APPS = [ 'corsheaders', 'rest_framework', 'rest_framework.authtoken', 'django_database.apps.DjangoDatabaseConfig', 'rest_api.apps.RestApiConfig', 'front', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] Now, I understand that django needs to know that there is a frontend app to connect to, but in front directory are those files: settings.py urls.py admin.py apps.py tests.py views.py I'm not really sure, but why does python files are in frontend ? Without urls.py and 'views.pyfiles django server startup fails with some linking error tofront`. urls.py from django.urls import path from .views import index urlpatterns = [ path('', index) ] views.py from django.shortcuts import render def index(request, *args, **kwargs): return render(request, 'front/index.html') I wonder what is this magic ? Searching trough some tutorials covering django rest and react app connection some of them does apply this strategy, but some does not. Can someone explain ? Haven't found any solution in django docs by now. Is there a better way of doing this ? Will CORS_ORIGIN_ALLOW_ALL or CORS_ORIGIN_WHITELIST be the same ?
- 
        How to restrict access by user groups in Django class based view?VIEW Problem: I want to use permission restriction in django class based views. if login user is belong from students group then i want to redirect to student-dash url. if user from teacher it's redirect to teach-dash url. if student user try to access the teacher dashboard then i want to restrict that student user from teacher dashboard and render 404 error? I would be grateful for any help. class STListView(ListView): queryset = Article.objects.exclude(story_status='sn') template_name = 'index_page.html' context_object_name = 'list' def get_context_data(self, **kwargs): context = super(STListView, self).get_context_data(**kwargs) group = self.request.user.groups.filter(user=self.request.user)[0] if group.name == "student": return HttpResponseRedirect(reverse('student-dash')) elif group.name == "teacher": return HttpResponseRedirect(reverse('teacher-dash')) elif group.name == "Manger": return HttpResponseRedirect(reverse('manger-dash')) return context
- 
        what is the path one have to follow in order to become Full Stack developer?I am the student of 4th semester in CS dept. so far i have learnt C++,OOP(java) and data structures(java) currently learning data base. I want to be a best full stack developer. but when search for the material to study. I get so many things like there is a node.js as well as there is Django , we have React for frontEnd and as well as Angular and many others. and when i google for the best path for full stack i get different answers. and I am afraid for this that what if... what i am learning today is not going to be useful for me in future. I am confused by seeing technologies frameworks libraries in order for be a full stack. I have earn a certificate on web developing by cs50. after that i can make small web application but i have no knowledge of what is happening behind the scene. They also gave the Introduction of REACT. and currently i am doing courses on JavaScript and next i am thinking to study all this instructed by cs50(David and Brain) deeply so that i can make more elegant and large scale web application. enter image description here …
- 
        Where is Django code inside my Django Application?When I created a Django application, where is the code of Django? I mean, the source code of the framework my app is using? Context: I've been receiving a NoReverseMatch error, and I think my urlpatterns are ok, so I want to debug the reverse function to see why it's failing.
- 
        How to work around heroku 30 seconds web request timeoutI am working on a Django App, which has been deployed on Heroku. A search function in the App uses an API to fetch data from a remote server. This server can take upto a minute to send a response. Problem is, Heroku's web request times out after 30 seconds. I have seen some similar problems here where people have been advised to make their code more efficient. Problem here is that I do not have control over the remote server and it's processes. Is there a way I can bypass this limit or should I be looking to host elsewhere?
- 
        why is external address lookup javascript causing: ValueError: Missing staticfiles manifest entry?My django App runs fine on local server and ok on heroku with DEBUG = False in settings.py. When DEBUG = True App crashes on Heroku with heroku log message: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/storage.py", line 423, in stored_name raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'libraries/ideal-postcode/dist/ideal-postcodes-autocomplete.js' So far as per many other questions raised for this issue. But, this javascript is listed fine in the json manifest created using manage.py collectstatic Snippet "libraries/ideal-postcode/dist/ideal-postcodes-autocomplete.js": "libraries\\ideal-postcode\\dist\\ideal-postcodes-autocomplete.b7dbf9579b39.js", "libraries/ideal-postcode/dist/ideal-postcodes-autocomplete.min.js": "libraries\\ideal-postcode\\dist\\ideal-postcodes-autocomplete.min.75f7e4c76264.js", This is the only static resource to cause a problem. The ideal-postcodes-autocomplete.js is an address lookup (used by my form fields). Snippet var IdealPostcodes; (function (IdealPostcodes) { IdealPostcodes.API_URL = "api.ideal-postcodes.co.uk"; IdealPostcodes.TLS = true; IdealPostcodes.VERSION = "v1"; IdealPostcodes.DEFAULT_TIMEOUT = 10000; /* * STRICT_AUTHORISATION forces authorization header usage on * autocomplete API which increases latency due to overhead * OPTIONS request */ IdealPostcodes.STRICT_AUTHORISATION = false; ; }) I've been through very many of the previous answers but no help and spent ages making changes and re-testing. Is the problem because the script calls an external resource? If so, how do I get around this problem. If not, what am I doing wrong? Can post the full ideal-postcodes-autocomplete.js if it helps.
- 
        I am getting error: Page not found in django. Please someone help me to solve the errormy urls.py page like this from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.index,name='index'), path('analyze/',views.analyze,name='analyze'), path('about/',views.about,name='about'), path('contact/',views.contact,name='contact'), ] my views.py page looks like this from django.http import HTTP Response from django.shortcuts import render def index(request): return render(request,'index.html') def analyze(request): djtext=request.GET.get('text','default') removepunc=request.GET.get('removepunc','off') fullcaps=request.GET.get('fullcaps','off') spaceremover=request.GET.get('spaceremover','off') charcounter=request.GET.get('charcounter','off') wordcounter=request.GET.get('wordcounter','off') print(djtext) #analyzed=djtext if removepunc == 'on': punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' analyzed="" for char in djtext: if char not in punctuations: analyzed=analyzed+char params={'purpose':'Remove punctuations','analyzed_text':analyzed} return render(request,'analyze.html',params) elif fullcaps=='on': # analyzed=djtext1 analyzed="" for i in djtext: if i==" ": analyzed=analyzed+" " else: analyzed=analyzed+i.upper() params={'purpose':'Capital Letter First','analyzed_text':analyzed} return render(request,'analyze.html',params) elif spaceremover == 'on': analyzed=djtext.replace(" ","") params={'purpose':'Space Remover','analyzed_text':analyzed} return render(request,'analyze.html',params) elif charcounter == 'on': counter=0 for char in djtext: if char==" ": continue else: counter=counter+1 params={'purpose':'Character Counter','analyzed_text':counter} return render(request,'analyze.html',params) elif wordcounter == 'on': counter=1 for char in djtext: if char==' ': counter=counter+1 params={'purpose':'Word Counter','analyzed_text':counter} return render(request,'analyze.html',params) else: return HttpResponse("Error") def about(request): return render(request,'about.html') def contact(request): return render(request,'contact.html') my index.html page-- Here I have shown only navbar part where error can be . My index.html page is in template/textutils and about and contact page are also in template/textutils. <div class="collapse navbar-collapse" id="navbarNavDropdown"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a> …