URL Configuration

The URLconf maps URL patterns to views.

Syntaxpath(route, view, name=...)

Django decides which view handles a request using a URLconf — a list of urlpatterns. The root URLconf lives in your project's urls.py.

The best practice is to give each app its own urls.py and include it from the project. This keeps routing modular.

Example

Example · python
# mysite/urls.py (project root)
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path("admin/", admin.site.urls),
    path("blog/", include("blog.urls")),   # delegate to the app
]

When to use it

  • A developer writes a URLconf in blog/urls.py so all blog routes are grouped away from the root urls.py.
  • A team structures an API by giving each app its own urls.py and including them under /api/ in the root router.
  • A developer reads the URLconf to debug a 404 error by checking which patterns are registered.

More examples

App-level URLconf

Defines app-level URL patterns that map paths to view functions.

Example · python
# blog/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path("", views.post_list, name="post-list"),
    path("<int:pk>/", views.post_detail, name="post-detail"),
]

Include app URLs in root config

Uses include() to mount the blog app's URLconf under the /blog/ prefix.

Example · python
# mysite/urls.py
from django.urls import path, include

urlpatterns = [
    path("blog/", include("blog.urls")),
]

Namespace URLs to avoid collisions

Adds an app namespace so URL names from different apps don't collide when reversed.

Example · python
# mysite/urls.py
urlpatterns = [
    path("blog/", include(("blog.urls", "blog"))),
]

# In a template:
# {% url 'blog:post-list' %}

Discussion

  • Be the first to comment on this lesson.