๐Ÿ“ Django

The {% url %} Tag in Django

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
205
๐ŸŒฑ
Level
Beginner

{% url %} is a template tag for generating URLs by route name.

Basic Usage

# urls.py
urlpatterns = [
    path('tasks/', views.task_list, name='task-list'),
    path('tasks/<int:pk>/', views.task_detail, name='task-detail'),
    path('tasks/new/', views.task_create, name='task-create'),
]
<!-- Simple URL -->
<a href="{% url 'task-list' %}">All tasks</a>
<!-- Result: /tasks/ -->

<!-- URL with parameter -->
<a href="{% url 'task-detail' pk=task.pk %}">{{ task.title }}</a>
<!-- Result: /tasks/42/ -->

<!-- Positional argument -->
<a href="{% url 'task-detail' task.pk %}">{{ task.title }}</a>

With Namespace

<a href="{% url 'tasks:list' %}">List</a>
<a href="{% url 'tasks:detail' pk=task.pk %}">Details</a>

Saving to a Variable

{% url 'task-detail' pk=task.pk as task_url %}
<a href="{{ task_url }}">Link</a>

<!-- Useful for conditional rendering -->
{% url 'task-edit' pk=task.pk as edit_url %}
{% if edit_url %}
  <a href="{{ edit_url }}">Edit</a>
{% endif %}

Multiple Parameters

# url: /courses/<course_slug>/lessons/<lesson_pk>/
path('<slug:course_slug>/lessons/<int:lesson_pk>/', views.lesson_detail, name='lesson-detail'),
{% url 'lesson-detail' course_slug=course.slug lesson_pk=lesson.pk %}

Why {% url %} Is Better Than Hardcoding

<!-- Bad: hardcoded path -->
<a href="/tasks/{{ task.pk }}/">Task</a>

<!-- Good: when the URL changes in urls.py, templates update automatically -->
<a href="{% url 'task-detail' pk=task.pk %}">Task</a>

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

Search in Django

You can start with simple Django ORM filters and move to PostgreSQL features when you...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 279
๐Ÿ“

Swagger Documentation with drf-spectacular

drf-spectacular generates an OpenAPI 3.0 schema and Swagger UI for DRF.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 563
๐Ÿ“

settings.py: Django Configuration

settings.py is the central configuration file for a Django project.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 315

Did you like the article?

Subscribe to our updates and be the first to receive new articles. Grow with PyLand!