When I first started working with Django, one of the common tasks I encountered was extracting URL parameters. Whether it’s grabbing a user ID from the URL path or reading query strings to filter data, handling URL parameters is essential for building dynamic web applications.
In this article, I’ll share practical methods to get URL parameters in Django, based on my years of experience developing Python web applications. I’ll walk you through step-by-step examples, so you can confidently capture parameters from URLs and use them effectively in your views.
URL Parameters in Django
URL parameters generally come in two flavors:
- Path parameters – These are parts of the URL path, like
/users/123/, where123is a parameter. - Query parameters – These are key-value pairs appended after a
?in the URL, like/search/?q=django.
Django makes it straightforward to access both types, but the approach differs slightly. Let’s dive into each method.
Read Create a Contact Form with Django and SQLite
Method 1: Get Path Parameters Using URL Patterns
The most common way to get parameters in Django is through URL patterns. This is useful when you want to capture a specific value as part of the URL path.
For example, imagine you’re building a site for a US-based book store, and you want to show details of a book by its ISBN number in the URL like this: /books/9780134685991/.
Here’s how you can capture the ISBN as a path parameter.
Step 1: Define URL Pattern
In your urls.py, define a URL pattern with a named parameter:
from django.urls import path
from . import views
urlpatterns = [
path('books/<str:isbn>/', views.book_detail, name='book_detail'),
]Here, <str:isbn> captures the ISBN as a string and passes it to the view.
Step 2: Access Parameter in View
In your views.py, define the view function to accept the parameter:
from django.http import HttpResponse
def book_detail(request, isbn):
# For demonstration, just return the ISBN received
return HttpResponse(f"Book ISBN: {isbn}")You can see the output in the screenshot below.

When you visit /books/9780134685991/, Django will pass "9780134685991" to the book_detail view as the isbn argument.
Why I like this method:
It’s clean, RESTful, and makes URLs user-friendly and SEO-optimized. It also leverages Django’s URL dispatcher, which is efficient and easy to maintain.
Check out Add Google reCAPTCHA to Django Form
Method 2: Get Query Parameters from the URL
Sometimes, you want to get parameters that aren’t part of the URL path but appended as query strings, like /search/?q=python&category=programming.
Django provides easy access to these through the request.GET dictionary.
Example: Search Books by Query
Imagine you want to implement a search feature on your US book store site where users can search by keyword and filter by category.
Step 1: URL Pattern
Since query parameters are not part of the URL pattern, you only need a basic URL:
from django.urls import path
from . import views
urlpatterns = [
path('search/', views.search_books, name='search_books'),
]Step 2: Access Query Parameters in View
In views.py:
from django.http import HttpResponse
def search_books(request):
query = request.GET.get('q', '') # Default to empty string if not provided
category = request.GET.get('category', 'all') # Default to 'all'
# For demonstration, just echo the parameters
return HttpResponse(f"Search Query: {query}, Category: {category}")If you visit /search/?q=python&category=programming, the response will be:
Search Query: python, Category: programming
Why this method is useful:
Query parameters allow for flexible filtering and searching without changing the URL structure. You can easily add or remove parameters as needed.
Read Build a Django Contact Form with Email
Method 3: Use Django Class-Based Views to Get URL Parameters
If you prefer class-based views (CBVs), accessing URL parameters is just as straightforward.
Let’s revisit the book detail example using Django’s DetailView.
Step 1: Define URL Pattern
from django.urls import path
from .views import BookDetailView
urlpatterns = [
path('books/<str:isbn>/', BookDetailView.as_view(), name='book_detail'),
]Step 2: Create the View
from django.views.generic.detail import DetailView
from .models import Book # Assuming you have a Book model
class BookDetailView(DetailView):
model = Book
template_name = 'book_detail.html'
slug_field = 'isbn'
slug_url_kwarg = 'isbn'Here, slug_url_kwarg tells Django which URL parameter to use to look up the book.
Step 3: Access Query Parameters in CBVs
You can access query parameters inside any CBV method, like get() or get_context_data():
class BookDetailView(DetailView):
model = Book
template_name = 'book_detail.html'
slug_field = 'isbn'
slug_url_kwarg = 'isbn'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
filter_param = self.request.GET.get('filter', 'none')
context['filter'] = filter_param
return contextThis way, you can combine path parameters and query parameters seamlessly.
Check out How to Use Python Django pre_save
Method 4: Handle Multiple URL Parameters
Sometimes, you want to capture multiple parameters from the URL path.
For example, suppose you want to show orders by a user in a specific state, like /orders/12345/CA/.
Step 1: Define URL Pattern
from django.urls import path
from . import views
urlpatterns = [
path('orders/<int:user_id>/<str:state>/', views.user_orders, name='user_orders'),
]Step 2: Access in View
from django.http import HttpResponse
def user_orders(request, user_id, state):
return HttpResponse(f"Orders for User ID: {user_id} in State: {state}")This method is handy when you want to filter data based on multiple criteria directly in the URL.
Read Run Python Script in Django
Tips When Working with URL Parameters in Django
- Always validate parameters before using them, especially if they come from the URL, to avoid security issues.
- Use Django’s converters (
int:,str:,slug:,uuid:) in URL patterns to enforce parameter types. - For optional parameters, consider using query parameters or default values in views.
- When dealing with query parameters, use
request.GET.get()with default values to avoidNoneTypeerrors. - Remember to URL-encode query parameters when generating URLs to handle special characters.
Getting URL parameters in Django is a fundamental skill that opens the door to building powerful, dynamic web applications. Whether you’re capturing user IDs, search queries, or filtering data by multiple parameters, Django’s flexible URL routing and request handling make it easy.
By combining path parameters and query strings, you can design clean, SEO-friendly URLs and provide rich user experiences. I hope these methods and examples help you confidently handle URL parameters in your Django projects.
If you have any questions or want to share your own tips, feel free to leave a comment below!
Other Django articles you may also like:
- How to Encrypt and Decrypt Passwords in Django
- Python Django Concatenate String
- Python Django Round to Two Decimal Places

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.