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.

DEFAULT_COMPONENTS_FOLDER_NAME: ClassVar[str] = '_components'
__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.

__repr__() str[source]

Debug representation.

__eq__(other: object) bool[source]

Return True when the other backend has the same pages configuration.

__hash__() int[source]

Hash from pages config including extra roots and skip names.

generate_urls() list[URLPattern | URLResolver][source]

Yield app routes first when app_dirs is set, then root pages dirs.

class next.urls.backends.RouterBackend[source]

Pluggable source of URLPattern and URLResolver entries.

abstractmethod generate_urls() list[URLPattern | URLResolver][source]

Patterns contributed by this backend to the project URLconf.

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.

classmethod is_filesystem_discovery_router(obj: object) bool[source]

Whether obj is a router instance that walks pages trees (duck typing).

classmethod create_backend(config: dict[str, Any]) RouterBackend[source]

Instantiate the backend class named by config[“BACKEND”].

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.

__init__() None[source]

Empty backend list until first iteration.

__repr__() str[source]

Debug representation with backend count.

__len__() int[source]

Return the number of configured backends.

__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.

parse_url_pattern(url_path: str) tuple[str, dict[str, str]][source]

Return the Django path string and parameter names for url_path.

prepare_url_name(url_path: str) str[source]

Python-safe name for reverse from a filesystem-style url_path.

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.

__init__(skip_dir_names: Iterable[str], *, components_folder_name: str, register_components: bool) None[source]

Remember which dirs to skip and whether to register component roots.

walk(pages_path: Path) Generator[tuple[str, Path], None, None][source]

Yield (url_path, page_file), where url_path is the route trail.

next.urls.dispatcher.scan_pages_tree(pages_path: Path, skip_dir_names: Iterable[str] = (), *, components_folder_name: str = '_components', register_components: bool = False) Generator[tuple[str, Path], None, None][source]

Walk a tree for page.py (and virtual pages) without a router instance.

Reverse Helpers

next.urls.reverse.page_reverse(path_template: str = '', *, namespace: str = 'next', **kwargs: object) str[source]

Reverse a file-router page URL from its directory-tree template.

next.urls.reverse.with_query(base: str, **overrides: object) str[source]

Return base with its query string updated by overrides.

None values drop their key from the result. Multi-valued keys can be set by passing a list/tuple value.

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
can_handle(param: Parameter, context: object) bool[source]

Return True when the parameter expects HttpRequest and a request exists.

resolve(_param: Parameter, context: object) object[source]

Return the request from the resolution context.

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
can_handle(param: Parameter, _context: object) bool[source]

Return True when the parameter uses a DUrl annotation.

resolve(param: Parameter, context: object) object[source]

URL value for the parameter, coerced when the annotation names a type.

class next.urls.markers.UrlKwargsProvider[source]

Fill parameters by name from url_kwargs.

priority = 70
can_handle(param: Parameter, context: object) bool[source]

Return True when url_kwargs contains this parameter name.

resolve(param: Parameter, context: object) object[source]

Raw URL value for the parameter, coerced to the annotation when possible.

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

HttpRequestProvider

Supplies the HttpRequest object for any parameter annotated HttpRequest or HttpRequest | None.

UrlByAnnotationProvider

Supplies a URL kwarg value for parameters annotated with DUrl[...].

UrlKwargsProvider

Supplies raw URL kwargs by parameter name when no annotation is present.

QueryParamProvider

Supplies request.GET values for parameters annotated with DQuery[...].

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

str

Any captured string.

Returned unchanged.

int

Decimal digit string.

int(value).

float

Decimal float string.

float(value).

bool

"1", "true", "yes" map to True, anything else to False.

Boolean.

UUID

Canonical UUID string, or an already parsed UUID.

UUID instance.

Decimal

Numeric string parseable by Decimal.

Decimal instance.

date

ISO 8601 date accepted by date.fromisoformat.

date instance.

datetime

ISO 8601 datetime accepted by datetime.fromisoformat.

datetime instance.

See Dependency Injection and File Router for the narrative coverage of each marker.

Signals

The URL subsystem fires two signals.

route_registered.

Sent by FileRouterBackend once per registered route, including virtual template.djx routes, with the url_path and file_path keyword arguments.

router_reloaded.

Sent by the router manager class after the router rebuilds, with no keyword arguments. The sender is the RouterManager class.

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, the BACKEND path, and per-backend DIRS/APP_DIRS/PAGES_DIR/OPTIONS keys.

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.

next.urls.checks.check_next_pages_configuration(*_args: object, **_kwargs: object) list[CheckMessage][source]

Validate DEFAULT_PAGE_BACKENDS inside merged NEXT_FRAMEWORK.

next.urls.checks.check_url_patterns(*_args: object, **_kwargs: object) list[CheckMessage][source]

Collect patterns from routers and flag duplicate Django path strings.

See Also

See also

File Router for the topic guide. URL Reversing for the reverse helpers. URL Router for the dispatcher internals.