path() and URL Parameters
Use path() to define routes and capture typed values from the URL.
Syntax
path("post/<int:id>/", view)The path() function connects a URL pattern to a view. Wrap a segment in angle brackets to capture it, optionally with a path converter like int, str or slug to convert and validate the value.
Captured values are passed to your view as keyword arguments.
Example
# blog/urls.py
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("post/<int:id>/", views.detail, name="detail"),
path("tag/<slug:tag>/", views.by_tag, name="by_tag"),
]
# views.detail(request, id) receives id as an intWhen to use it
- A developer uses path('<int:pk>/') to capture a numeric post ID from the URL and pass it to the view.
- A blog uses path('<slug:slug>/') to create human-readable SEO-friendly URLs for each article.
- A developer uses path('') to map the root of an app namespace to a list view.
More examples
Basic static path
Maps the literal string 'about/' to the about view with a named URL pattern.
from django.urls import path
from . import views
urlpatterns = [
path("about/", views.about, name="about"),
]Integer path converter
Captures an integer from the URL and passes it as the pk keyword argument to the view.
urlpatterns = [
path("posts/<int:pk>/", views.post_detail, name="post-detail"),
]
# view signature:
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
...Slug and string converters
Shows the slug and str path converters for human-readable and arbitrary string URL segments.
urlpatterns = [
path("articles/<slug:slug>/", views.article_detail, name="article-detail"),
path("users/<str:username>/", views.profile, name="profile"),
]
Discussion