URLs
If you remember the urls.py
file of our application, you will note that each URL is identified with a name given as the third argument to the path()
function:
urlpatterns = [
path("", views.index, name="index"),
path("about-us", views.about_us, name="about_us"),
path("courses", views.courses, name="courses"),
path("courses/json", views.courses_json, name="courses_json")
]
This name lets you to generate URLs in templates using the {% url ... %}
syntax. For example:
<a href='{% url "courses" %}'>View courses</a>
Is rendered as:
<a href='/myapp/courses'>View courses</a>
The benefit of using the url
tag instead of manually writing the link is that you can modify the URL at any time without having to modify the templates where it is referenced.
So if we now change this:
path("courses", views.courses, name="courses"),
For this:
path("courses-list", views.courses, name="courses"),
The link we wrote earlier still works, since it was rendered at runtime from the URL identifier ("courses"
).
In Python, the equivalent of the {% url ... %}
syntax is the reverse()
function. You would probably use something like this in your views:
>>> from django.urls import reverse
>>> reverse("courses")
'/myapp/courses-list'
The above code is intended to run in Django's shell, which we haven't introduced yet. We will using it in the next chapters.