URLs Reference¶
Module Summary¶
next.urls exposes the router backends RouterBackend and FileRouterBackend.
It also exposes the RouterFactory and RouterManager that build and own them.
The URLPatternParser for bracket-segment parsing is part of the public surface.
It also exposes the page_reverse and with_query reverse helpers, the get_multi_values query reader, and the Django integration name app_name.
The parameter providers and the dependency markers DUrl (captured path segments) and DQuery (query string parameters) round out the public surface.
Public API¶
Backends¶
Pluggable router backend contract, file router, and backend factory.
The RouterBackend ABC defines the contract every router implementation must satisfy. FileRouterBackend is the built-in implementation that discovers page.py (and virtual template.djx) entries under app and optional root page trees. RouterFactory maps dotted backend paths to classes and instantiates them from DEFAULT_PAGE_BACKENDS config dicts.
- class next.urls.backends.FileRouterBackend(pages_dir: str | None = None, *, app_dirs: bool | None = None, extra_root_paths: list[Path] | None = None, skip_dir_names: frozenset[str] | None = None, components_folder_name: str | None = None, options: dict[str, Any] | None = None)[source]¶
Discover page.py (and virtual pages) under app and optional root trees.
- __init__(pages_dir: str | None = None, *, app_dirs: bool | None = None, extra_root_paths: list[Path] | None = None, skip_dir_names: frozenset[str] | None = None, components_folder_name: str | None = None, options: dict[str, Any] | None = None) None[source]¶
Configure pages dir, extra roots, skip-dir names, and narrowed OPTIONS.
- class next.urls.backends.RouterBackend[source]¶
Pluggable source of URLPattern and URLResolver entries.
- class next.urls.backends.RouterFactory[source]¶
Build RouterBackend instances from DEFAULT_PAGE_BACKENDS-style dicts.
- classmethod register_backend(name: str, backend_class: type[RouterBackend]) None[source]¶
Map a dotted backend path to a class for create_backend.
- classmethod is_filesystem_discovery_router_class(router_class: object) bool[source]¶
Return True if router_class implements the filesystem page-tree API.
Manager¶
urlpatterns is a list subclass that recollects router and form-action patterns from the active backends on each access.
The backends themselves are cached by router_manager and are only rebuilt when router_manager.reload() runs or when DEFAULT_PAGE_BACKENDS changes.
A route added after import is therefore visible without a process restart, but each access still iterates the cached backend list rather than walking the page tree again.
RouterManager owns the active backend list, and the router_manager singleton exposes reload() to rebuild it.
Router manager, lazy urlpatterns list, and settings-reload wiring.
RouterManager owns the list of active RouterBackend instances and rebuilds it from NEXT_FRAMEWORK[“DEFAULT_PAGE_BACKENDS”] whenever framework settings change. _LazyUrlPatterns is a list-subclass used as Django’s urlpatterns so the first access triggers router and form-action resolution without walking the page tree at import time.
- class next.urls.manager.RouterManager[source]¶
Load RouterBackend instances from NEXT_FRAMEWORK and iterate them.
- __iter__() Generator[URLPattern | URLResolver, None, None][source]¶
All patterns from each backend, loading config on first use.
- __getitem__(index: int) RouterBackend[source]¶
Return the backend at the given index.
- reload() None[source]¶
Rebuild backends from DEFAULT_PAGE_BACKENDS and notify listeners.
The Django URL resolver caches resolved patterns. The cache is cleared here so the next request sees the freshly built backend list. The router_reloaded signal fires after the rebuild and the cache flush so receivers observe a consistent state.
Parser¶
Map bracket segments in file-based URL paths to Django converters.
The URLPatternParser turns a filesystem-style logical URL trail into a Django path pattern. Bracket syntax [name] maps to <str:name>, [int:id] maps to <int:id>, and [[args]] maps to <path:args>.
- class next.urls.parser.URLPatternParser[source]¶
Map bracket segments in a file-based path to Django path converters.
The url_path string is the logical URL trail built from directory names. An empty string means the tree root. It is not a pathlib.Path. The on-disk file is the second value from the page-tree scanner.
Dispatcher¶
Deep import path
The names in next.urls.dispatcher are not re-exported from next.urls.
Import them through the submodule path when a custom backend or test needs to call them directly.
Walk filesystem page trees once to emit routes and register components.
FilesystemTreeDispatcher performs a single depth-first walk per page-tree root. It yields (url_path, page_file) pairs for every discovered page.py (plus virtual template.djx-only pages), and registers _components folders it encounters along the way.
- class next.urls.dispatcher.FilesystemTreeDispatcher(skip_dir_names: Iterable[str], *, components_folder_name: str, register_components: bool)[source]¶
Run one depth-first walk: routes per node or skip component folders.
Reverse Helpers¶
Markers¶
Dependency injection markers and providers for URL-derived parameters.
DUrl is an annotation marker used in @context and view-derived callables to pull a value from URL kwargs. DQuery is the parallel marker that reads request.GET query-string parameters. The provider classes plug into the next.deps resolver via RegisteredParameterProvider and expose HttpRequest, DUrl[…] values, raw URL kwargs by name, and DQuery[…] values.
- class next.urls.markers.DQuery[source]¶
Annotation marker for a request.GET parameter.
Use DQuery[str], DQuery[int], DQuery[bool], or DQuery[float] for scalar values, or DQuery[list[T]] for multi-value parameters. The list form accepts the plain repeated form ?brand=a&brand=b, the qs-style bracket suffix ?brand[]=a&brand[]=b emitted by axios and other front-end clients, and the comma-delimited form ?brand=a,b produced by qs.stringify with the comma array format. The provider returns the parameter default when the key is absent, or None when no default is given.
- class next.urls.markers.DUrl[source]¶
Annotation for a captured URL path parameter with optional type coercion.
Use DUrl[SomeType] to read the captured segment that matches the parameter name and coerce it. Use DUrl[“param”] to read a named segment without coercion. Use DUrl[“param”, SomeType] to read a named segment and coerce it, which is the form to reach for when the parameter name differs from the captured segment name.
- classmethod __class_getitem__(item: object) object[source]¶
Build the marker for the type, named-key, and named-key-with-type forms.
A plain type follows the standard generic path. A string, or a (string, type) tuple, is wrapped so the provider can read the captured segment by an explicit name rather than the parameter name.
- class next.urls.markers.HttpRequestProvider[source]¶
Supply HttpRequest from context.request.
The provider claims parameters annotated as HttpRequest or HttpRequest | None. The optional form lets handlers keep request: HttpRequest | None = None for direct unit-test calls without giving up dependency injection.
- priority = 50¶
- class next.urls.markers.QueryParamProvider[source]¶
Resolve DQuery[…] parameters from request.GET.
- priority = 80¶
- can_handle(param: inspect.Parameter, context: ResolutionContext) bool[source]¶
Return True for DQuery[…] annotations when a request is present.
- resolve(param: inspect.Parameter, context: ResolutionContext) object[source]¶
Pull the value from request.GET and coerce it to the annotated type.
- class next.urls.markers.UrlByAnnotationProvider[source]¶
Fill DUrl[…] parameters from url_kwargs.
- priority = 60¶
- class next.urls.markers.UrlKwargsProvider[source]¶
Fill parameters by name from url_kwargs.
- priority = 70¶
- next.urls.markers.get_multi_values(request: HttpRequest, name: str) list[str][source]¶
Return all values for name from
request.GET.Tries three wire formats in order: plain repeated keys (
?brand=a&brand=b), bracket suffix (?brand[]=a&brand[]=b), and comma-delimited (?brand=a,b). Returns an empty list when the parameter is absent in all three forms.
Parameter Providers¶
The following provider classes are registered with the next.deps resolver at startup.
They are exported from next.urls for introspection and for authors writing custom providers that delegate to them.
Provider |
What it supplies |
|---|---|
|
Supplies the |
|
Supplies a URL kwarg value for parameters annotated with |
|
Supplies raw URL kwargs by parameter name when no annotation is present. |
|
Supplies |
See Dependency Resolver for the full provider registration sequence and the resolution order.
DUrl and DQuery both accept str, int, bool, float, UUID, Decimal, date, and datetime.
DQuery additionally accepts list[T] for any of those scalars.
The following table is the canonical coercion reference. A value that fails to parse falls back to the raw captured string rather than raising.
Annotation type |
Accepted wire values |
Result |
|---|---|---|
|
Any captured string. |
Returned unchanged. |
|
Decimal digit string. |
|
|
Decimal float string. |
|
|
|
Boolean. |
|
Canonical UUID string, or an already parsed |
|
|
Numeric string parseable by |
|
|
ISO 8601 date accepted by |
|
|
ISO 8601 datetime accepted by |
|
See Dependency Injection and File Router for the narrative coverage of each marker.
Signals¶
The URL subsystem fires two signals.
route_registered.Sent by
FileRouterBackendonce per registered route, including virtualtemplate.djxroutes, with theurl_pathandfile_pathkeyword arguments.router_reloaded.Sent by the router manager class after the router rebuilds, with no keyword arguments. The sender is the
RouterManagerclass.
See Signals Reference and Signals for the wider signal catalog.
Checks¶
next.urls.checks registers Django system checks that validate the URL configuration at startup.
check_next_pages_configuration.Validates the
NEXT_FRAMEWORK['DEFAULT_PAGE_BACKENDS']structure, theBACKENDpath, and per-backendDIRS/APP_DIRS/PAGES_DIR/OPTIONSkeys.check_duplicate_url_parameters.Fails with next.E028 when one route repeats a captured parameter name.
check_url_patterns.Fails with next.E015 when two file routes resolve to the same Django path string.
System checks for the URL routing subsystem.
- next.urls.checks.check_duplicate_url_parameters(*_args: object, **_kwargs: object) list[CheckMessage][source]
Fail when the same bracket parameter name is repeated in one route.
See Also¶
See also
File Router for the topic guide. URL Reversing for the reverse helpers. URL Router for the dispatcher internals.