Reverse URL in Templates
A snippet showing how to reverse URLs inside templates.
# models.py
from django.db import models
class Author(models.Model):
username = models.SlugField(unique=True)
# admin.py
from django.contrib import admin
from .models import Author
@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
list_display = ("username",)
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path("authors/<slug:username>/", views.author_detail, name="author-detail"),
]
# template.html
<a href="{% url 'author-detail' username=author.username %}">View profile</a>
Explanation:
-
The
{% url %}tag reverses named URLs and inserts parameters by name. - Prefer keyword args to reduce errors when routes change.
- Category URLs & Routing
- Total Views 774
- Last Modified 31 March, 2026
- Tags #urls #reverse #templates #routing
Previous snippet
Optional Trailing Slashes
Next snippet