📝 Django

The {% url %} Tag in Django

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
66
🌱
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

📝

pytest-django: Testing Django

Охватываемые темы: Installation, @pytest.mark.djangodb, Fixtures, Testing views.

📅 30.06.2026 👁️ 132
📝

Django: Template Tags

Template tags are logic inside HTML. Unlike {{ variable }} which only outputs a value,...

📅 30.06.2026 👁️ 84
📝

Django: Static Files

Static files are CSS, JavaScript, images, and fonts. Django handles them in a specific way:...

📅 30.06.2026 👁️ 73

Did you like the article?

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