Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 77 ยท URLs and Views

URL Routing

Learn Django URL routing: urlpatterns, path converters, re_path, include, namespaces, and how resolve() and reverse() map URLs to views and back.

A web framework must answer one question for every request: which code handles this URL? In Django, the answer lives in the URL configuration (often called the URLconf): a list of patterns, each pointing to a view. It also works in the opposite direction, so that your code and templates can ask "what is the URL of the article page?" without hard-coding any strings.

This lesson covers urlpatterns, path() and its converters, regular expressions with re_path(), splitting routes across apps with include(), namespaces, and the two functions that bridge URLs and views: resolve() and reverse(). You will run all of them live.

urlpatterns and path()

When a request arrives, Django imports the module named by the ROOT_URLCONF setting and reads its urlpatterns list. It checks the patterns in order and uses the first one that matches. Each entry is created with path(route, view, name=None):

Python
from django.urls import path
from . import views

urlpatterns = [
    path("", views.home, name="home"),
    path("articles/<int:year>/<slug:slug>/", views.article_detail, name="article-detail"),
]
  • route is a string. Angle brackets capture part of the URL and pass it to the view as a keyword argument. No leading slash is needed, and the query string (?page=2) is never part of the match.
  • view is a function, or SomeView.as_view() for class-based views.
  • name gives the pattern a stable identifier. Always name your URLs: it is what makes reverse() and the {% url %} tag possible.

Path converters

A capture like <int:year> has two parts: a converter (int) that decides which text matches and what Python type the view receives, and a name (year) that becomes the argument name. The built-in converters:

Converter Matches Python type
str Any non-empty text without / (the default if no converter is given) str
int Zero or a positive integer int
slug Letters, digits, hyphens and underscores str
uuid A formatted UUID uuid.UUID
path Any non-empty text including / str

int does not match negative numbers or letters, so /articles/abc/x/ simply does not match that pattern, and Django moves on to the next one (or ends in a 404). This is a gentle form of validation: your view never sees non-numeric data for an int capture.

The path converter is for things like file paths where slashes belong to the value. Because it swallows slashes, place such routes carefully.

You can register your own converter with register_converter(). A converter is a class with a regex string plus to_python() and to_url() methods. The second example below defines one for four-digit years.

Resolving and reversing

Django offers two directions:

  • resolve(path) takes a URL path and returns a ResolverMatch describing the view, its arguments and its name. This is what the framework does for every request.
  • reverse(name, args=..., kwargs=...) takes a URL name and returns the path. Use it whenever you need a link: in views (redirect), in models (get_absolute_url) and in templates ({% url 'article-detail' year=2025 slug='x' %}).
flowchart LR
    U["URL path<br/>/articles/2025/django-urls/"] -- "resolve()" --> V["view + arguments<br/>article_detail(year=2025, slug='django-urls')"]
    V -- "reverse()" --> U

resolve() and reverse() are inverse operations over the same list of patterns.

Reversing means a URL appears in exactly one place. If you later change articles/ to news/, every link updates automatically. Hard-coded URLs in HTML scatter that knowledge and break when routes change.

Python path, converters, resolve and reverse

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the output, notice that the year captured by <int:year> is the integer 2025, whereas the year from the regular expression is the string '1999'. Converters change types; plain regular expression groups always give strings.

re_path(): regular expressions

When converters are not enough, re_path() accepts a regular expression. Use named groups ((?P<name>...)) so values arrive as keyword arguments. Plain unnamed groups become positional arguments, and Django cannot mix the two forms in a single pattern: when any named group exists, unnamed ones are ignored.

Python
from django.urls import re_path

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

Prefer path() whenever a converter suffices; patterns are easier to read. Reach for re_path() for unusual shapes such as an optional extension or alternation (^(?P<kind>photos|videos)/$).

include(): splitting routes across apps

A project with ten apps does not keep hundreds of routes in one file. Each app owns a urls.py with its own urlpatterns, and the project mounts them at a prefix with include():

Python
# mysite/urls.py
from django.urls import include, path

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

Django matches and strips the blog/ prefix, then continues matching the remainder against blog.urls. An app's URLs therefore never need to know where they are mounted, so the same app can be moved to a different prefix by editing one line.

flowchart TD
    R["ROOT_URLCONF"] --> B["blog/ -> include(blog.urls)"]
    R --> S["shop/ -> include(shop.urls)"]
    B --> B1["'' -> index"]
    B --> B2["post/int:pk/ -> detail"]
    S --> S1["'' -> index"]
    S --> S2["item/int:pk/ -> detail"]

include() nests URLconfs; the resolver walks the tree and joins the pieces of the matched path.

Namespaces

Two apps will often both want a URL named index or detail. Without help, reverse("detail") would be ambiguous. Namespaces solve this. You declare an application namespace in the app's urls.py:

Python
# blog/urls.py
app_name = "blog"

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

Then you reverse with a colon: reverse("blog:detail", args=[12]) or {% url 'blog:detail' 12 %}. If the same app is mounted twice (say, for two sites), each mount can have its own instance namespace via include(..., namespace="news"), so you can reverse to a specific instance with reverse("news:detail", args=[12]).

The next example mounts one set of patterns twice, defines a custom converter and shows why pattern order matters. (Here include() receives a (patterns, app_name) tuple, which is the in-code equivalent of app_name = "blog" in a urls.py file.)

Python include, namespaces and ordering

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the results. The custom converter turned 2025 into an int when resolving and padded 7 to 0007 when reversing. The same two blog patterns answered both /blog/... and /news/..., and ResolverMatch reports both the instance namespace (news) and the application namespace (blog). Finally, with items/<str:name>/ listed first, the "new" page was unreachable because <str:name> also matches new. Put specific patterns before general ones.

Trailing slashes and APPEND_SLASH

Django's convention is to end URLs with a slash (/about/). When CommonMiddleware is active (it is by default) and the setting APPEND_SLASH is True, a request for /about that matches no pattern but would match /about/ is redirected to the slash version. That works for GET requests; a POST to the slashless URL cannot be redirected safely and raises an error in debug mode. Pick one style, include the slash in your patterns and use reverse()/{% url %} so you never type URLs by hand.

Common mistakes

  • Forgetting name=: you cannot reverse an unnamed URL.
  • A leading slash in the route (path("/about/")): this never matches, because Django strips the leading slash before matching.
  • Catch-all patterns first: <str:name> or <path:rest> placed above specific routes swallows them.
  • A name collision between apps: use app_name and reverse with the namespace.
  • Using re_path for everything: converters are clearer and give typed arguments.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Django checks URL patterns in order. What happens when two patterns could match the same URL?

    Order matters. Put specific patterns before general ones, or the general pattern shadows them.
  2. 2. What type does a view receive for the capture <int:year>?

    The int converter's to_python() method turns the matched text into a Python int before calling the view.
  3. 3. Why give URL patterns a name?

    Named patterns let you generate URLs from one source of truth, so changing a route updates every link.
  4. 4. What is app_name = "blog" in an app's urls.py used for?

    The application namespace avoids clashes between URL names of different apps and gives you the 'namespace:name' form.
  5. 5. Which converter should you use for a value that may contain slashes, such as a file path?

    str stops at a slash; path matches any text including slashes.

Summary

  • urlpatterns is checked top to bottom; the first match wins, so put specific routes first.
  • path() uses converters (str, int, slug, uuid, path) that capture and convert values; re_path() handles regular expressions with named groups.
  • include() mounts an app's URLconf under a prefix; app_name and namespace prevent name clashes.
  • resolve() maps a URL to a view, and reverse() maps a name back to a URL; always name patterns and avoid hard-coded URLs.
  • Custom converters register with register_converter() and provide regex, to_python() and to_url().
  • Unmatched URLs end in a 404; APPEND_SLASH redirects slashless GET requests when the slash version exists.

Next lesson: Function-Based Views.