In Django, URL mapping (also known as URLconf) is the process of linking web addresses (URLs) to the views that handle them. This system forms the backbone of how users interact with your Django application through the browser.
This article walks you through how URL mapping works in Django, how to define and manage URLs, how to include app-specific URLs, and how to use named routes and parameters effectively.
What is URL Mapping?
URL mapping tells Django what code to run when a user visits a certain URL.
For example:
-
Visiting
/about/
should call theabout
view -
Visiting
/post/5/
should call thepost_detail
view withid=5
Django does this through a URL configuration file, typically named urls.py
.
Step 1: Project-Level URL Configuration
When you create a Django project, Django generates a default urls.py
file in your project folder (e.g., mysite/urls.py
).
Example:
# mysite/urls.py
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
Add Your App’s URL Mapping:
Suppose you have an app named blog
. First, include the app’s URL configuration:
# mysite/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls')), # Include app-level URLs
]
Step 2: App-Level URL Configuration
Inside your app (blog/
), create a urls.py
if it doesn’t exist:
touch blog/urls.py
Example:
# blog/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('about/', views.about, name='about'),
]
Now:
-
/blog/
→views.home
-
/blog/about/
→views.about
✨ Step 3: Using Dynamic URL Parameters
Django allows you to capture parts of the URL as parameters.
Example:
# blog/urls.py
urlpatterns = [
path('post/<int:id>/', views.post_detail, name='post_detail'),
]
In views.py
:
def post_detail(request, id):
return HttpResponse(f"Post ID is {id}")
URL: /blog/post/42/
will display:
"Post ID is 42"
Supported Converters:
Converter | Example | Description |
---|---|---|
str |
<str:name> |
Matches any non-empty string |
int |
<int:id> |
Matches integers |
slug |
<slug:title> |
Letters, numbers, hyphens |
uuid |
<uuid:uid> |
UUIDs |
path |
<path:sub> |
Like str but includes slashes |
Step 4: Using name=
for Reverse URL Resolution
Naming your URLs lets you refer to them in templates or views without hardcoding the path.
Example:
# blog/urls.py
path('about/', views.about, name='about')
Use in templates:
<a href="{% url 'about' %}">About Us</a>
Use in views:
from django.shortcuts import redirect
redirect('about')
This keeps your code maintainable and DRY.
Step 5: Namespacing URLs (For Multiple Apps)
If you have multiple apps with overlapping URL names (like multiple home
routes), use namespaces.
In blog/urls.py
:
app_name = 'blog'
urlpatterns = [
path('', views.home, name='home'),
]
In main urls.py
:
path('blog/', include('blog.urls', namespace='blog')),
Template Usage:
<a href="{% url 'blog:home' %}">Go to Blog</a>
Example: Complete URL Flow
blog/views.py
:
from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to the blog!")
def post_detail(request, id):
return HttpResponse(f"Viewing Post #{id}")
blog/urls.py
:
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.home, name='home'),
path('post/<int:id>/', views.post_detail, name='post_detail'),
]
mysite/urls.py
:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('blog/', include('blog.urls', namespace='blog')),
]
URLs:
-
/blog/
→ Home view -
/blog/post/3/
→ Post detail for post #3
✅ Best Practices for Django URLs
-
✅ Always use
name=
for reverse URL resolution -
✅ Organize each app’s URLs in
app/urls.py
-
✅ Use
include()
to manage complex projects -
✅ Use namespaces for scalable multi-app projects
-
✅ Prefer descriptive URL patterns like
/blog/post/5/
over query strings
⚠️ Common Pitfalls
Mistake | Issue | Fix |
---|---|---|
❌ Missing include() in project urls.py |
App URLs won't be routed | Use include('app.urls') |
❌ Missing trailing slashes | May lead to unexpected redirects | Use trailing slashes consistently |
❌ Not naming your URLs | Hard to use {% url %} in templates |
Always use name= |
❌ Forgetting .as_view() for CBVs |
Error when routing class views | Use MyView.as_view() |
❌ Parameter type mismatch | URL pattern fails to match | Ensure types match in path converter |
Conclusion
Django’s URL mapping system is powerful and flexible. It allows you to structure your URLs cleanly and route them to appropriate views with minimal code. Understanding how to use path()
, dynamic segments, include()
, and namespaces is essential to building well-organized Django applications.