Hi there!
I got into this issue that I’ve spent hours yesterday trying to understand. I found a fix, but I have no idea how it works!
Summary of the issue:
The URL template tag in my base HTML is being resolved into the unexpected/unwanted URL. The URL tag ‘should’ point to the base (home) page URL (the same page it currently sits on) but its weirdly pointing to another URL (‘/todo/’).
My files:
Currently, I only have 1 app (“demo_app”).
Here’s my project folder’s main urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path("", include("demo_app.urls")),
path("todo/", include("demo_app.urls"))
]
And here’s my demo_app’s urls.py:
urlpatterns = [
path("", views.home, name="base"),
path("todo/", views.todo, name="todo_list")
]
I’m using 2 HTML files in this example, one called “base.html” and another called “toDoList.html” which I don’t even know how it’s getting to.
“base.html”
(has some boiler plate code but im only including the relevant section)
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="{% url 'base' %}">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li>
</ul>
toDoList.html
{% extends "base.html" %}
{%block title%} The todo list {%endblock%}
{%block content%}
<h1>This is your TODO list</h1>
{%endblock%}
and finally my demo_app.views file:
from django.shortcuts import render, HttpResponse
# Create your views here.
def base(request):
return render(request, "base.html")
def todo(request):
return render(request, "toDoList.html")
So what’s exactly happening??
When I kickstart the server and go to the base page (http://127.0.0.1:8000/), the nav-link “Home” which has the template tag {% url ‘base’ %} points to “/todo/” for some bizarre reason. I expect it to point to “/”, the base page, which is the one it sits on. I have no idea how the views.todo function is even being called.
What’s the weird fix that you found?
If I go to my project’s urls.py, and i change the order of the urls to:
urlpatterns = [
path('admin/', admin.site.urls),
path("todo/", include("demo_app.urls")),
path("", include("demo_app.urls"))
]
everything works as expected. How? That’s what I would like to know!!
Thanks a lot in advance!!!