How to Use re_path in Django for URL Routing
In Django,
re_path is used to define URL patterns using regular expressions, allowing flexible and complex matching. You import re_path from django.urls and use it in your urlpatterns list to map URLs to views with regex patterns.Syntax
The re_path function takes a regular expression pattern as the first argument and a view function or class as the second. Optionally, you can provide a name for the URL pattern to reference it later.
- pattern: A raw string with a regex to match the URL path.
- view: The view function or class to call when the pattern matches.
- name (optional): A string to name the URL pattern for reverse lookups.
python
from django.urls import re_path urlpatterns = [ re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive, name='year_archive'), ]
Example
This example shows how to use re_path to match URLs with a year parameter and call a view that receives the year as an argument.
python
from django.urls import re_path from django.http import HttpResponse # Simple view that returns the year from the URL def year_archive(request, year): return HttpResponse(f"Articles from year: {year}") urlpatterns = [ re_path(r'^articles/(?P<year>[0-9]{4})/$', year_archive, name='year_archive'), ]
Output
When visiting /articles/2023/, the page shows: Articles from year: 2023
Common Pitfalls
- Forgetting to use raw strings (prefix
r) for regex patterns can cause errors because backslashes are treated as escape characters. - Not anchoring the regex pattern properly can lead to unexpected matches.
- Using
path()when you need regex flexibility;re_pathis required for complex patterns. - Missing named groups in regex when the view expects keyword arguments.
python
from django.urls import re_path # Wrong: missing raw string prefix, will cause errors urlpatterns = [ re_path('^articles/(?P<year>[0-9]{4})/$', views.year_archive), # Incorrect ] # Right: use raw string for regex urlpatterns = [ re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive), # Correct ]
Quick Reference
| Parameter | Description |
|---|---|
| pattern | Regular expression string to match URL paths |
| view | View function or class to handle the matched URL |
| name | Optional name for the URL pattern for reverse lookups |
Key Takeaways
Use re_path with raw string regex patterns to define flexible URL routes in Django.
Always include named groups in regex if your view expects keyword arguments.
Use the name parameter to easily reference URLs elsewhere in your project.
Avoid common mistakes like missing raw string prefix or incorrect regex anchoring.
re_path is ideal when path() cannot express the needed URL pattern.