2. RegEx in URL
Django provides re_path()
(regular expression-based path matching) as an alternative to path()
, allowing more complex URL patterns.
1. When to Use re_path
You should use re_path()
when:
- You need flexible URL patterns (e.g., support multiple formats).
- You require complex validation (e.g., specific ID ranges).
path()
is too simple for your needs.
2. Basic Example of re_path
Instead of using path()
, we use re_path()
from django.urls
and match the URL using a regular expression.
Example: Using re_path
for Book Details
urls.py
from django.urls import re_pathfrom . import views
urlpatterns = [ re_path(r'^book/(?P<book_id>\d+)/$', views.book_detail, name='book_detail'),]
✔ Regex Explanation (r'^book/(?P<book_id>\d+)/$'
):
^book/
→ URL must start with"book/"
(?P<book_id>\d+)
→ Captures numbers (\d+
), named asbook_id
/$
→ Ensures the URL ends with/
views.py
from django.http import HttpResponse
def book_detail(request, book_id): return HttpResponse(f"Book ID: {book_id}")
✅ Example URLs that match:
http://127.0.0.1:8000/book/1/
http://127.0.0.1:8000/book/123/
🚫 Examples that don’t match:
http://127.0.0.1:8000/book/abc/
(only digits are allowed)http://127.0.0.1:8000/book/12
(missing/
at the end)
3. Using re_path
for Slugs
If you need to capture both numbers and letters, use a slug-based regex.
urls.py
urlpatterns = [ re_path(r'^book/(?P<book_slug>[\w-]+)/$', views.book_detail_by_slug, name='book_detail_by_slug'),]
✔ Regex Explanation (r'^book/(?P<book_slug>[\w-]+)/$'
):
[\w-]+
→ Matches letters, numbers, and dashes (-
)- Named capture
(?P<book_slug>...)
makes it accessible in views
views.py
def book_detail_by_slug(request, book_slug): return HttpResponse(f"Book Slug: {book_slug}")
✅ Example URLs that match:
http://127.0.0.1:8000/book/django-basics/
http://127.0.0.1:8000/book/python-tips/
4. Using Multiple Patterns in One re_path
You can combine multiple patterns into a single re_path()
.
Example: Match ID or Slug
urlpatterns = [ re_path(r'^book/(?P<book_param>\d+|[\w-]+)/$', views.book_detail_mixed, name='book_detail_mixed'),]
views.py
def book_detail_mixed(request, book_param): return HttpResponse(f"Book ID or Slug: {book_param}")
✅ Matches both IDs and slugs:
http://127.0.0.1:8000/book/123/
http://127.0.0.1:8000/book/django-for-beginners/
5. Should You Use re_path
or path
?
Feature | path() | re_path() |
---|---|---|
Simple, readable | ✅ Yes | ❌ No (uses regex) |
Best for numeric IDs | ✅ Yes (<int:id> is simple) | ✅ Yes |
Allows complex patterns | ❌ No | ✅ Yes (e.g., \d+ or [\w-]+ ) |
Supports optional parts | ❌ No | ✅ Yes (with ? ) |
Recommended for most cases | ✅ Yes | ❌ No (use only if needed) |
🚀 Best Practice: Use path()
unless you need advanced regex features.
6. When to Use re_path
?
Use re_path()
if:
✅ You need optional URL parameters (?
).
✅ You want to match multiple patterns in one rule.
✅ You need custom validation beyond Django’s built-in converters.
Otherwise, stick with path()
for better readability.