1. Basics
1. URL Parameters
Django provides path converters to capture different types of parameters in URLs.
Path Converter | Description | Example URL |
---|---|---|
<int:var> | Matches integers | /book/1/ |
<str:var> | Matches any string | /book/python/ |
<slug:var> | Matches slug format | /book/django-basics/ |
<uuid:var> | Matches UUID values | /book/550e8400-e29b-41d4-a716-446655440000/ |
1.2 Using URL Parameters in urls.py
Let’s define different URL patterns in urls.py
.
from django.urls import pathfrom . import views # Import views
urlpatterns = [ path('book/<int:book_id>/', views.book_detail, name='book_detail'), # Integer parameter path('book/<slug:book_slug>/', views.book_detail_by_slug, name='book_detail_by_slug'), # Slug parameter]
1.3 Handling Parameters in Views
Now, define functions in views.py
to handle these parameters.
(a) Integer ID Parameter
from django.http import HttpResponse
def book_detail(request, book_id): return HttpResponse(f"Book ID: {book_id}")
- This view extracts the
book_id
from the URL and returns it as a response. - Example URL:
http://127.0.0.1:8000/book/1/
→ Output: “Book ID: 1”
(b) Slug Parameter
def book_detail_by_slug(request, book_slug): return HttpResponse(f"Book Slug: {book_slug}")
- This view extracts the
book_slug
from the URL. - Example URL:
http://127.0.0.1:8000/book/django-for-beginners/
→ Output: “Book Slug: django-for-beginners”
1.4 Fetching Data from the Database
Instead of returning a simple HttpResponse
, you can fetch data from your Book
model.
Example with Django ORM
from django.shortcuts import render, get_object_or_404from .models import Book # Import your model
def book_detail(request, book_id): book = get_object_or_404(Book, id=book_id) # Fetch book from DB return render(request, 'book_detail.html', {'book': book})
def book_detail_by_slug(request, book_slug): book = get_object_or_404(Book, slug=book_slug) # Fetch book from DB return render(request, 'book_detail.html', {'book': book})
- Now, if a book with the given ID or slug exists, it will be displayed using the
book_detail.html
template.
1.5 URL Reversal (Generating URLs Dynamically)
If you want to generate URLs dynamically in Django templates or views, use the reverse()
function or {% url %}
template tag.
In Templates
<a href="{% url 'book_detail' book.id %}">View Book</a>
- This will generate a URL like
/book/1/
.
In Views (Python Code)
from django.urls import reversefrom django.shortcuts import redirect
def some_view(request): return redirect(reverse('book_detail', args=[1])) # Redirects to /book/1/
2. Multiple URL Parameters
To accept multiple URL parameters in Django, you can simply define multiple path converters in your urls.py
file and pass them to your view function. Each parameter in the URL can be captured and passed as an argument to the view function.
Example: Handling Multiple URL Parameters
Let’s say you want to capture two parameters: id
(book ID) and slug
(book slug or title), from a URL like:
books/1/some-book-slug/
You can define a URL pattern like this:
Step 1: Define the URL pattern with multiple parameters
In urls.py
, you can define the URL to capture both the id
and slug
parameters:
from django.urls import pathfrom . import views
urlpatterns = [ path('books/<int:id>/<slug:slug>/', views.book_detail, name='book_detail'),]
Here:
<int:id>
captures an integer parameter (book ID).<slug:slug>
captures a slug (which is a URL-friendly string, often used for titles).
Step 2: Modify the view to accept multiple parameters
In views.py
, the view function should accept both the id
and slug
parameters and use them accordingly.
from django.shortcuts import render, get_object_or_404from .models import Book
def book_detail(request, id, slug): # Fetch the book by both the id and slug book = get_object_or_404(Book, pk=id, slug=slug)
# Render the book detail page with the book data return render(request, 'book_detail.html', {'book': book})
In this view:
id
andslug
are the parameters captured from the URL.get_object_or_404(Book, pk=id, slug=slug)
fetches the book from the database by bothid
andslug
.
Example URL:
Now, if you visit the following URL:
/books/1/some-book-slug/
The view will:
- Capture
id = 1
- Capture
slug = "some-book-slug"
- Query the database for a book with
id=1
andslug="some-book-slug"
. - Render the book details in the
book_detail.html
template.
Step 3: Handling optional parameters (if needed)
If you need some parameters to be optional, you can use re_path
and regular expressions or add default values.
For example, if the slug
is optional, you can define the URL like this:
from django.urls import path, re_pathfrom . import views
urlpatterns = [ path('books/<int:id>/', views.book_detail, name='book_detail'), # Just id path('books/<int:id>/<slug:slug>/', views.book_detail, name='book_detail_slug'), # id and slug]
In the view, you can handle the case where the slug
might not be present:
from django.shortcuts import render, get_object_or_404from .models import Book
def book_detail(request, id, slug=None): if slug: # Fetch book by both id and slug book = get_object_or_404(Book, pk=id, slug=slug) else: # Fetch book by id only if slug is not provided book = get_object_or_404(Book, pk=id)
return render(request, 'book_detail.html', {'book': book})
With this setup, the URL pattern /books/1/
would still work and fetch the book by id
only, while /books/1/some-book-slug/
would fetch the book by both id
and slug
.