url Tag in Django Template

In Django, the {% url %} template tag is used to generate URLs by reversing the URL patterns defined in your urls.py file. This approach promotes cleaner code and helps avoid hard-coding URLs in your templates.

Here’s how you can use the {% url %} tag:

Syntax: The {% url %} tag syntax is:

{% url 'viewname' arg1 arg2 %}

Here, 'viewname' is the name of the URL pattern you defined in your urls.py. arg1, arg2, etc., are the arguments that the URL pattern expects.

Example: Suppose you have a URL pattern defined in your urls.py like this:

# urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('article/<int:year>/', views.year_archive, name='news-year-archive'),

You can use the {% url %} tag in your template like this:

<!-- In your Django template -->
<a href="{% url 'news-year-archive' 2022 %}">View 2022 Archive</a>

This will resolve to the URL for viewing the 2022 archive, assuming your app is hosted at the root.

Using the {% url %} tag helps ensure your templates remain easy to maintain, particularly if you later decide to change URL patterns. The links in your templates will update automatically to reflect the new patterns.