URLs
Route requests to views.
URLs are typically the "entrypoint" to your app. Virtually all request handling up to this point happens behind the scenes, and then you decide how to route specific URL patterns to your views.
The URLS_ROUTER
is the primary router that handles all incoming requests. It is defined in your app/settings.py
file. This will typically point to a Router
class in your app.urls
module.
# app/settings.py
URLS_ROUTER = "app.urls.AppRouter"
The root router often has an empty namespace (""
) and some combination of individual paths and sub-routers.
# app/urls.py
from plain.urls import Router, path, include
from plain.admin.urls import AdminRouter
from . import views
class AppRouter(Router):
namespace = ""
urls = [
include("admin/", AdminRouter),
path("about/", views.AboutView, name="about"), # A named URL
path("", views.HomeView), # An unnamed URL
]
Reversing URLs
In templates, you will use the {{ url("<url name>") }}
function to look up full URLs by name.
<a href="{{ url('about') }}">About</a>
And the same can be done in Python code with the reverse
(or reverse_lazy
) function.
from plain.urls import reverse
url = reverse("about")
A URL path has to include a name
attribute if you want to reverse it. The router's namespace
will be used as a prefix to the URL name.
from plain.urls import reverse
url = reverse("admin:dashboard")
URL args and kwargs
URL patterns can include arguments and keyword arguments.
# app/urls.py
from plain.urls import Router, path
from . import views
class AppRouter(Router):
namespace = ""
urls = [
path("user/<int:user_id>/", views.UserView, name="user"),
path("search/<str:query>/", views.SearchView, name="search"),
]
These will be accessible inside the view as self.url_args
and self.url_kwargs
.
# app/views.py
from plain.views import View
class SearchView(View):
def get(self):
query = self.url_kwargs["query"]
print(f"Searching for {query}")
# ...
To reverse a URL with args or kwargs, simply pass them in the reverse
function.
from plain.urls import reverse
url = reverse("search", query="example")
There are a handful of built-in converters that can be used in URL patterns.
from plain.urls import Router, path
from . import views
class AppRouter(Router):
namespace = ""
urls = [
path("user/<int:user_id>/", views.UserView, name="user"),
path("search/<str:query>/", views.SearchView, name="search"),
path("post/<slug:post_slug>/", views.PostView, name="post"),
path("document/<uuid:uuid>/", views.DocumentView, name="document"),
path("path/<path:subpath>/", views.PathView, name="path"),
]
Package routers
Installed packages will often provide a URL router to include in your root URL router.
# plain/assets/urls.py
from plain.urls import Router, path
from .views import AssetView
class AssetsRouter(Router):
"""
The router for serving static assets.
Include this router in your app router if you are serving assets yourself.
"""
namespace = "assets"
urls = [
path("<path:path>", AssetView, name="asset"),
]
Import the package's router and include
it at any path you choose.
from plain.urls import include, Router
from plain.assets.urls import AssetsRouter
class AppRouter(Router):
namespace = ""
urls = [
include("assets/", AssetsRouter),
# Your other URLs here...
]
1from plain.utils.functional import lazy
2
3from .exceptions import NoReverseMatch
4from .resolvers import get_ns_resolver, get_resolver
5
6
7def reverse(viewname, *args, **kwargs):
8 resolver = get_resolver()
9
10 if not isinstance(viewname, str):
11 view = viewname
12 else:
13 *path, view = viewname.split(":")
14
15 current_path = None
16
17 resolved_path = []
18 ns_pattern = ""
19 ns_converters = {}
20 for ns in path:
21 current_ns = current_path.pop() if current_path else None
22 # Lookup the name to see if it could be an app identifier.
23 try:
24 app_list = resolver.app_dict[ns]
25 # Yes! Path part matches an app in the current Resolver.
26 if current_ns and current_ns in app_list:
27 # If we are reversing for a particular app, use that
28 # namespace.
29 ns = current_ns
30 elif ns not in app_list:
31 # The name isn't shared by one of the instances (i.e.,
32 # the default) so pick the first instance as the default.
33 ns = app_list[0]
34 except KeyError:
35 pass
36
37 if ns != current_ns:
38 current_path = None
39
40 try:
41 extra, resolver = resolver.namespace_dict[ns]
42 resolved_path.append(ns)
43 ns_pattern += extra
44 ns_converters.update(resolver.pattern.converters)
45 except KeyError as key:
46 if resolved_path:
47 raise NoReverseMatch(
48 "{} is not a registered namespace inside '{}'".format(
49 key, ":".join(resolved_path)
50 )
51 )
52 else:
53 raise NoReverseMatch(f"{key} is not a registered namespace")
54 if ns_pattern:
55 resolver = get_ns_resolver(
56 ns_pattern, resolver, tuple(ns_converters.items())
57 )
58
59 return resolver.reverse(view, *args, **kwargs)
60
61
62reverse_lazy = lazy(reverse, str)