TExcelTAD
Home › Django › Django URLs

Django URLs

When a request arrives, Django looks at the path (/books/42/) and walks through a list called urlpatterns in the root URLconf — the module named by the ROOT_URLCONF setting. The first pattern that matches wins, and its view is called. If nothing matches, Django returns 404 Not Found.

python
# mysite/urls.py
from django.urls import path
from books import views

urlpatterns = [
    path("", views.home, name="home"),
    path("books/", views.book_list, name="book_list"),
    path("books/<int:pk>/", views.book_detail, name="book_detail"),
]

path() and converters

path(route, view, kwargs=None, name=None) matches a route string. Parts in angle brackets capture values from the URL and pass them to the view as keyword arguments. A converter before the colon checks and converts the value:

Converter Matches Python type
str (default) any non-empty text without / str
int zero or positive integers int
slug letters, digits, - and _ str
uuid a UUID such as 075194d3-6885-417e-a8a8-6c931e272f00 uuid.UUID
path any non-empty text including / str
python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"])
django.setup()
from django.http import HttpResponse
from django.urls import path
from django.test import Client

def show(request, **kwargs):
    parts = [f"{k}={v!r} ({type(v).__name__})" for k, v in kwargs.items()]
    return HttpResponse(", ".join(parts))

urls.urlpatterns = [
    path("books/<int:pk>/", show),
    path("tags/<slug:tag>/", show),
    path("archive/<int:year>/<int:month>/", show),
    path("files/<path:name>", show),
]

c = Client()
for url in ["/books/42/", "/books/abc/", "/tags/django-tips/",
            "/archive/2026/10/", "/files/docs/guide.pdf"]:
    r = c.get(url)
    print(f"{url:<22} {r.status_code}  {r.content.decode() if r.status_code == 200 else ''}")
/books/42/             200  pk=42 (int)
/books/abc/            404
/tags/django-tips/     200  tag='django-tips' (str)
/archive/2026/10/      200  year=2026 (int), month=10 (int)
/files/docs/guide.pdf  200  name='docs/guide.pdf' (str)

Notice that /books/abc/ never reaches the view: the int converter refuses it, no other pattern matches, so Django answers 404 by itself.

Naming URLs and reverse()

Hard-coding paths like "/books/42/" all over your code is fragile. Give each pattern a name and let Django build the URL with reverse() (in Python) or the {% url %} tag (in templates). Change the route once and every link follows.

python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
                   TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}])
django.setup()
from django.http import HttpResponse
from django.urls import path, reverse, resolve
from django.template import Template, Context

def book_detail(request, pk):
    return HttpResponse(f"Book {pk}")

def home(request):
    return HttpResponse("Home")

urls.urlpatterns = [
    path("", home, name="home"),
    path("library/books/<int:pk>/", book_detail, name="book_detail"),
]

print(reverse("home"))
print(reverse("book_detail", args=[7]))
print(reverse("book_detail", kwargs={"pk": 8}))

match = resolve("/library/books/9/")
print(match.url_name, match.func.__name__, match.kwargs)

t = Template('<a href="{% url "book_detail" pk=3 %}">Book 3</a>')
print(t.render(Context()))
/
/library/books/7/
/library/books/8/
book_detail book_detail {'pk': 9}
<a href="/library/books/3/">Book 3</a>

resolve() is the reverse of reverse(): it tells you which view and arguments a path maps to.

include() and namespaces

Large projects split URLs per app. include() mounts another list of patterns under a prefix. Setting app_name in the included module creates a namespace, so two apps can both have a URL named "index" without clashing — you reverse them as "books:index" and "blog:index".

python · try it yourself
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"])
django.setup()
from django.http import HttpResponse
from django.urls import path, include, reverse
from django.test import Client

def books_index(request):
    return HttpResponse("All books")

def blog_index(request):
    return HttpResponse("All posts")

def blog_post(request, slug):
    return HttpResponse(f"Post: {slug}")

# what books/urls.py and blog/urls.py would contain
books_urls = ([path("", books_index, name="index")], "books")
blog_urls = ([path("", blog_index, name="index"),
              path("<slug:slug>/", blog_post, name="post")], "blog")

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

print(reverse("books:index"), reverse("blog:index"), reverse("blog:post", args=["hello-django"]))
c = Client()
print(c.get("/blog/hello-django/").content.decode())
print(c.get("/books/").content.decode())
/books/ /blog/ /blog/hello-django/
Post: hello-django
All books

In a real project, the included module is a file:

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

app_name = "blog"
urlpatterns = [
    path("", views.index, name="index"),
    path("<slug:slug>/", views.post, name="post"),
]

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

re_path for regular expressions

When converters aren't enough, re_path() accepts a regular expression with named groups. Captured values are always strings:

python
from django.urls import re_path

urlpatterns = [
    re_path(r"^archive/(?P<year>[0-9]{4})/
quot;, views.year_archive), ]

Tip: End routes with a slash ("books/"). With the default APPEND_SLASH = True and CommonMiddleware, a request to /books is redirected to /books/ automatically.

Test yourself

Which route captures 42 from /books/42/ as an integer named pk?

  1. path("books/<pk>/", ...)
  2. path("books/<int:pk>/", ...)
  3. path("books/{pk}/", ...)
  4. path("books/:pk/", ...)

What does reverse("book_detail", args=[5]) do?

  1. Calls the view with pk 5
  2. Builds the URL path for the pattern named book_detail
  3. Deletes book 5
  4. Redirects the user

Why set app_name in an app's urls.py?

  1. To register the app in INSTALLED_APPS
  2. To create a URL namespace such as blog:index
  3. To speed up URL matching
  4. It is required for every URLconf