Named URLs & reverse()
Named URLs let you reference URL patterns by name instead of hardcoding paths. The reverse() function and {% url %} template tag generate URLs from names. This makes your code resilient to URL changes.
15 min•By Priygop Team•Updated 2026
Why Named URLs?
- Avoid hardcoding URLs — if URLs change, code doesn't break
- name='post-detail' in path() gives the pattern a name
- {% url 'post-detail' pk=1 %} in templates generates /blog/1/
- reverse('post-detail', args=[1]) in views generates /blog/1/
- reverse_lazy() for class attributes (evaluated at module load time)
- App namespaces: {% url 'blog:detail' pk=1 %} avoids name conflicts
Named URLs & reverse()
Named URLs & reverse()
# blog/urls.py
# app_name = 'blog' # App namespace
# urlpatterns = [
# path('', views.post_list, name='post-list'),
# path('<int:pk>/', views.post_detail, name='post-detail'),
# path('create/', views.post_create, name='post-create'),
# ]
# In views — use reverse()
# from django.urls import reverse
# from django.shortcuts import redirect
#
# def post_create(request):
# if request.method == 'POST':
# post = Post.objects.create(title=request.POST['title'])
# # Redirect to the new post's detail page
# return redirect(reverse('blog:post-detail', args=[post.pk]))
# return render(request, 'blog/create.html')
# In templates — use {% url %}
# <a href="{% url 'blog:post-list' %}">All Posts</a>
# <a href="{% url 'blog:post-detail' pk=post.pk %}">{{ post.title }}</a>
# <form action="{% url 'blog:post-create' %}" method="post">Tip
Tip
Each model class maps to one database table. Each attribute maps to a column. Django handles SQL creation through migrations.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Not setting on_delete for ForeignKey. Django requires it. Use CASCADE for child deletion, PROTECT to prevent parent deletion.
Practice Task
Note
(1) Create a model with CharField, IntegerField, DateField. (2) Add __str__ method. (3) Run makemigrations and migrate.
Quick Quiz
Key Takeaways
- Named URLs let you reference URL patterns by name instead of hardcoding paths.
- Avoid hardcoding URLs — if URLs change, code doesn't break
- name='post-detail' in path() gives the pattern a name
- {% url 'post-detail' pk=1 %} in templates generates /blog/1/