URL Patterns & Path Converters
Django uses path() and re_path() to define URL patterns. Path converters like <int:id>, <str:slug>, and <uuid:pk> let you capture dynamic values from URLs and pass them as arguments to your view functions.
20 min•By Priygop Team•Updated 2026
URL Patterns
- path(route, view, kwargs, name) — Main URL function
- route — URL pattern string with path converters
- <int:pk> — Captures an integer, e.g., /blog/42/
- <str:slug> — Captures a string (no slashes), e.g., /blog/my-post/
- <slug:slug> — Same as str but allows hyphens/underscores
- <uuid:id> — Captures a UUID value
- <path:rest> — Captures everything including slashes
- re_path() — Regex-based patterns for complex matching
Path Converters Example
Path Converters Example
# blog/urls.py
# from django.urls import path
# from . import views
# urlpatterns = [
# # Static URL
# path('', views.post_list, name='post-list'),
#
# # Integer converter — matches /blog/1/, /blog/42/
# path('<int:pk>/', views.post_detail, name='post-detail'),
#
# # String/Slug converter — matches /blog/my-first-post/
# path('<slug:slug>/', views.post_by_slug, name='post-slug'),
#
# # Multiple converters
# path('<int:year>/<int:month>/', views.archive, name='archive'),
# ]
# blog/views.py
# def post_detail(request, pk):
# # pk is automatically an integer
# post = Post.objects.get(pk=pk)
# return render(request, 'blog/detail.html', {'post': post})
#
# def post_by_slug(request, slug):
# post = Post.objects.get(slug=slug)
# return render(request, 'blog/detail.html', {'post': post})Tip
Tip
QuerySets are lazy — they don't hit the database until evaluated (iteration, slicing, list()). Chain filters freely without performance cost.
Diagram
Loading diagram…
QuerySets are LAZY — no DB hit until evaluated.
Common Mistake
Warning
Using .get() without try/except. It raises DoesNotExist if no match and MultipleObjectsReturned if multiple. Use .filter().first() for safe access.
Practice Task
Note
(1) Use filter(), exclude(), order_by() in the shell. (2) Chain multiple filters. (3) Try .get() with a non-existent pk.
Quick Quiz
Key Takeaways
- Django uses path() and re_path() to define URL patterns.
- path(route, view, kwargs, name) — Main URL function
- route — URL pattern string with path converters
- <int:pk> — Captures an integer, e.g., /blog/42/