Episode 14 of 32

URL Parameters

Capture dynamic values from URLs — pass article slugs or IDs as URL parameters to display specific content.

URL Parameters

To show a specific article, you need to capture a dynamic value from the URL — like a slug or an ID — and pass it to the view function.

Defining Dynamic URLs

# articles/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.article_list, name='article_list'),
    path('<slug:slug>/', views.article_detail, name='article_detail'),
]

<slug:slug> captures a URL-safe string and passes it to the view as a keyword argument called slug.

Path Converters

ConverterMatchesExample
intPositive integers<int:id>42
strAny non-empty string (no slashes)<str:name>hello
slugLetters, numbers, hyphens, underscores<slug:slug>my-article

The Detail View

# articles/views.py
from django.shortcuts import render
from .models import Article

def article_detail(request, slug):
    article = Article.objects.get(slug=slug)
    return render(request, 'articles/article_detail.html', {
        'article': article
    })

The slug parameter comes from the URL pattern. We use it to query the database for the matching article.

How It Works

User visits /articles/my-first-post/
    ↓
URL pattern: <slug:slug> → captures "my-first-post"
    ↓
Calls article_detail(request, slug="my-first-post")
    ↓
Queries: Article.objects.get(slug="my-first-post")
    ↓
Renders the detail template with the article

Key Takeaways

  • <type:name> in URL patterns captures dynamic values
  • Captured values are passed to the view as keyword arguments
  • Use slug for readable URLs; int for numeric IDs
  • The view uses the captured value to query the database