URL Parameters

URL Parameters allow you to capture dynamic values from a URL and pass them to a view.

Instead of creating separate URLs for every resource, you can use parameters to make URLs dynamic.

Why Use URL Parameters?

Suppose you have multiple blog posts:

/blog/1/
/blog/2/
/blog/3/

Instead of creating separate URL patterns for each post, Django can capture the ID dynamically.

Basic Syntax

path('blog/<int:id>/', view_function)

Here:

  • blog/ → Static part
  • <int:id> → Dynamic parameter
  • id → Variable name

Example

urls.py

from django.urls import path
from .views import blog_detail

urlpatterns = [
    path('blog/<int:id>/', blog_detail),
]

views.py

from django.http import HttpResponse

def blog_detail(request, id):
    return HttpResponse(f"Blog ID: {id}")

URL

http://127.0.0.1:8000/blog/5/

Output

Blog ID: 5

String Parameters

urls.py

path('user/<str:name>/', user_profile)

views.py

from django.http import HttpResponse

def user_profile(request, name):
    return HttpResponse(f"Welcome {name}")

URL

http://127.0.0.1:8000/user/tarun/

Output

Welcome tarun

Slug Parameters

A slug is a URL-friendly string commonly used in blogs and SEO-friendly URLs.

urls.py

path('post/<slug:slug>/', post_detail)

URL

http://127.0.0.1:8000/post/django-url-routing/

Captured Value

django-url-routing

UUID Parameters

Useful when working with unique identifiers.

urls.py

path('product/<uuid:id>/', product_detail)

Example URL

/product/550e8400-e29b-41d4-a716-446655440000/

Path Parameters

Captures an entire path including slashes.

urls.py

path('files/<path:file_path>/', file_view)

URL

/files/images/profile/user.jpg/

Captured Value

images/profile/user.jpg

Available Path Converters

ConverterDescriptionExample
strString (default)tarun
intInteger10
slugURL-friendly stringdjango-course
uuidUUID value550e8400-e29b
pathComplete pathimages/user.jpg

Multiple Parameters

urls.py

path('student/<int:id>/<str:name>/', student_detail)

views.py

from django.http import HttpResponse

def student_detail(request, id, name):
    return HttpResponse(f"ID: {id}, Name: {name}")

URL

/student/101/tarun/

Output

ID: 101, Name: tarun

URL Parameters with Class-Based Views

views.py

from django.views import View
from django.http import HttpResponse

class BlogDetailView(View):

    def get(self, request, id):
        return HttpResponse(f"Blog ID: {id}")

urls.py

path('blog/<int:id>/', BlogDetailView.as_view())

Real-World Example

urls.py

path('product/<int:id>/', product_detail)

views.py

from django.shortcuts import get_object_or_404
from .models import Product

def product_detail(request, id):
    product = get_object_or_404(Product, id=id)
    return HttpResponse(product.name)

When a user visits:

/product/15/

Django fetches the product with ID 15 from the database.