python / intermediate
Snippet
Django URL Routing and reverse() Resolution
Django's URL routing system uses named patterns with reverse resolution. The reverse() function generates URLs from their name and parameters, making your code more maintainable by decoupling URL structure from views. The app_name namespace prevents naming conflicts between apps.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# urls.pyfrom django.urls import pathfrom . import viewsapp_name = 'blog'urlpatterns = [path('article/<int:year>/<slug:slug>/', views.article_detail, name='article_detail'),path('archive/', views.archive, name='archive'),]# views.pyfrom django.shortcuts import get_object_or_404from django.urls import reversefrom .models import Articledef article_detail(request, year, slug):article = get_object_or_404(Article, pub_date__year=year, slug=slug)share_url = request.build_absolute_uri(reverse('blog:article_detail', args=[year, slug]))return render(request, 'blog/detail.html', {'article': article, 'share_url': share_url})def archive(request):archive_url = reverse('blog:archive') # /archive/return redirect(archive_url)
django
Breakdown
1
app_name = 'blog'
Namespaces the URL patterns for this app to avoid conflicts with other apps
2
path('article/<int:year>/<slug:slug>/', ...
Defines URL pattern with type converters: int and slug for dynamic segments
3
name='article_detail'
Names this pattern for reverse resolution in templates and views
4
request.build_absolute_uri(reverse(...))
Builds full absolute URL including domain for sharing purposes
5
reverse('blog:article_detail', args=[year, slug])
Reverses URL by app namespace and name, passing positional arguments