How to Use the url Tag in Django Templates
In Django templates, use the
{% url 'view_name' %} tag to generate URLs for views by their name defined in urls.py. This helps keep links dynamic and avoids hardcoding URLs. You can also pass arguments to the url tag to build URLs with parameters.Syntax
The url tag syntax in Django templates is:
{% url 'view_name' %}- generates the URL for the named view without parameters.{% url 'view_name' arg1 arg2 %}- passes positional arguments to the URL pattern.{% url 'view_name' key1=value1 key2=value2 %}- passes keyword arguments to the URL pattern.
Use quotes around the view name. Arguments must match the URL pattern parameters.
django
{% url 'view_name' %}
{% url 'view_name' arg1 arg2 %}
{% url 'view_name' key1=value1 key2=value2 %}Example
This example shows how to use the url tag to link to a view named article_detail that expects an id parameter.
django
{# urls.py #}
from django.urls import path
from . import views
urlpatterns = [
path('article/<int:id>/', views.article_detail, name='article_detail'),
]
{# template.html #}
<a href="{% url 'article_detail' 42 %}">Read Article 42</a>Output
<a href="/article/42/">Read Article 42</a>
Common Pitfalls
Common mistakes when using the url tag include:
- Forgetting quotes around the view name, e.g.,
{% url article_detail 42 %}instead of{% url 'article_detail' 42 %}. - Passing wrong or missing arguments that don't match the URL pattern.
- Using the
urltag for views without anameinurls.py. - Not loading the
urltag library in very old Django versions (before 1.5), but this is automatic in modern Django.
django
{# Wrong usage: missing quotes #}
<a href="{% url article_detail 42 %}">Read Article</a>
{# Correct usage #}
<a href="{% url 'article_detail' 42 %}">Read Article</a>Quick Reference
| Usage | Description |
|---|---|
| {% url 'view_name' %} | Generate URL for named view without parameters |
| {% url 'view_name' arg1 arg2 %} | Generate URL with positional arguments |
| {% url 'view_name' key1=value1 %} | Generate URL with keyword arguments |
| Quotes around view name | Required to identify the view name as a string |
| Named URL patterns | URL patterns must have a name to use with url tag |
Key Takeaways
Always use quotes around the view name in the url tag.
Pass arguments matching the URL pattern parameters to build dynamic URLs.
URL patterns must have a name to be referenced by the url tag.
The url tag helps avoid hardcoding URLs and keeps templates maintainable.
Common errors include missing quotes and incorrect arguments.