URL Dispatcher and Routing
URL Dispatcher and Routing
The URL Dispatcher is the front door of every Django application. It matches incoming HTTP request paths against a list of URL patterns, extracts dynamic parameters (like integers, slugs, or UUIDs) using Path Converters, and dispatches the request to the matching view callable.
1. Anatomy of path() and re_path()
2. Built-in Path Converters
Django includes five native path converters that both match patterns and typecast extracted URL parameters into native Python types:
| Path Converter | Matches | Python Type Passed to View | Example |
|---|---|---|---|
str (default) | Any non-empty string excluding / | str | <str:username> matches "alice" |
int | Zero or any positive integer | int | <int:pk> matches 42 -> passes 42 |
slug | ASCII letters, numbers, hyphens, underscores | str | <slug:post_slug> matches "django-orm-guide" |
uuid | Formatted UUID string | uuid.UUID | <uuid:id> matches "123e4567-e89b-..." |
path | Any non-empty string including / | str | <path:filepath> matches "media/docs/invoice.pdf" |
3. Creating Custom Path Converters
If standard converters do not fit your domain (e.g. 4-digit years or phone numbers), register a custom converter:
Register in urls.py:
4. Namespacing and URL Resolution
Always define app_name inside your app's urls.py:
Resolve URLs unambiguously across your project:
- In Python:
reverse("billing:invoice-detail", kwargs={"pk": 105}) - In Templates:
{% url 'billing:invoice-detail' pk=invoice.id %}
Practice Quiz
Serializers
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Class-Based Views (CBV) | Serializers |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.