``django.urls`` utility functions

فهرست فصل‌ها دانلود آرشیوناشر

Django Docs · نسخهٔ 33d2e5948a0b · BSD-3-Clause

=================================

`django.urls` utility functions

`reverse()`

The `reverse() function can be used to return an absolute path reference for a given view and optional parameters, similar to the url` tag:

`viewname can be a URL pattern name <naming-url-patterns> or the callable view object used in the URLconf. For example, given the following url`::

from news import views

path("archive/", views.archive, name="news-archive")

you can use any of the following to reverse the URL::

# using the named URL reverse("news-archive")

# passing a callable object # (This is discouraged because you can't reverse namespaced views this way.) from news import views

reverse(views.archive)

If the URL accepts arguments, you may pass them in `args`. For example::

from django.urls import reverse

def myview(request): return HttpResponseRedirect(reverse("arch-summary", args=[1945]))

You can also pass `kwargs instead of args`. For example:

pycon
>>> reverse("admin:app_list", kwargs={"app_label": "auth"})
'/admin/auth/'

`args and kwargs cannot be passed to reverse()` at the same time.

If no match can be made, `reverse() raises a ~django.urls.NoReverseMatch` exception.

The `reverse() function can reverse a large variety of regular expression patterns for URLs, but not every possible one. The main restriction at the moment is that the pattern cannot contain alternative choices using the vertical bar ("|"`) character. You can quite happily use such patterns for matching against incoming URLs and sending them off to views, but you cannot reverse such patterns.

The `current_app argument allows you to provide a hint to the resolver indicating the application to which the currently executing view belongs. This current_app argument is used as a hint to resolve application namespaces into URLs on specific application instances, according to the namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`.

The `urlconf` argument is the URLconf module containing the URL patterns to use for reversing. By default, the root URLconf for the current thread is used.

The `query keyword argument specifies parameters to be added to the returned URL. It can accept an instance of ~django.http.QueryDict (such as request.GET) or any value compatible with urllib.parse.urlencode. The encoded query string is appended to the resolved URL, prefixed by a ?`.

The `fragment keyword argument specifies a fragment identifier to be appended to the returned URL (that is, after the path and query string, preceded by a #`).

For example:

pycon
>>> from django.urls import reverse
>>> reverse("admin:index", query={"q": "biscuits", "page": 2}, fragment="results")
'/admin/?q=biscuits&page=2#results'
>>> reverse("admin:index", query=[("color", "blue"), ("color", 1), ("none", None)])
'/admin/?color=blue&color=1&none=None'
>>> reverse("admin:index", query={"has empty spaces": "also has empty spaces!"})
'/admin/?has+empty+spaces=also+has+empty+spaces%21'
>>> reverse("admin:index", fragment="no encoding is done")
'/admin/#no encoding is done'

The `query and fragment` arguments were added.

The string returned by `reverse() is already urlquoted <uri-and-iri-handling>`. For example:

pycon
    >>> reverse("cities", args=["Orléans"])
    '.../Orl%C3%A9ans/'

Applying further encoding (such as :func:`urllib.parse.quote`) to the output
of ``reverse()`` may produce undesirable results.

The view object can also be the result of calling ~django.views.generic.base.View.as_view if the same view object is used in the URLConf. Following the original example, the view object could be defined as:

python
    from django.views import View


    class ArchiveView(View): ...


    archive = ArchiveView.as_view()

However, remember that namespaced views cannot be reversed by view object.

`reverse_lazy()`

A lazily evaluated version of reverse()_.

It is useful for when you need to use a URL reversal before your project's URLConf is loaded. Some common cases where this function is necessary are:

  • providing a reversed URL as the `url` attribute of a generic class-based

view.

  • providing a reversed URL to a decorator (such as the `login_url` argument

for the django.contrib.auth.decorators.permission_required decorator).

  • providing a reversed URL as a default value for a parameter in a function's

signature.

The `query and fragment` arguments were added.

`resolve()`

The `resolve()` function can be used for resolving URL paths to the corresponding view functions. It has the following signature:

`path is the URL path you want to resolve. As with ~django.urls.reverse, you don't need to worry about the urlconf parameter. The function returns a ResolverMatch` object that allows you to access various metadata about the resolved URL.

If the URL does not resolve, the function raises a ~django.urls.Resolver404 exception (a subclass of ~django.http.Http404) .

The view function that would be used to serve the URL

The arguments that would be passed to the view function, as parsed from the URL.

All keyword arguments that would be passed to the view function, i.e. ~ResolverMatch.captured_kwargs and ~ResolverMatch.extra_kwargs.

The captured keyword arguments that would be passed to the view function, as parsed from the URL.

The additional keyword arguments that would be passed to the view function.

The name of the URL pattern that matches the URL.

The route of the matching URL pattern.

For example, if `path('users/<id>/', ...) is the matching pattern, route will contain 'users/<id>/'`.

The list of URL patterns tried before the URL either matched one or exhausted available patterns.

The application namespace for the URL pattern that matches the URL.

The list of individual namespace components in the full application namespace for the URL pattern that matches the URL. For example, if the `app_name is 'foo:bar', then app_names will be ['foo', 'bar']`.

The instance namespace for the URL pattern that matches the URL.

The list of individual namespace components in the full instance namespace for the URL pattern that matches the URL. i.e., if the namespace is `foo:bar, then namespaces will be ['foo', 'bar']`.

The name of the view that matches the URL, including the namespace if there is one.

A ResolverMatch object can then be interrogated to provide information about the URL pattern that matches a URL::

# Resolve a URL match = resolve("/some/path/") # Print the URL pattern that matches the URL print(match.url_name)

A ResolverMatch object can also be assigned to a triple::

func, args, kwargs = resolve("/some/path/")

One possible use of ~django.urls.resolve would be to test whether a view would raise a `Http404` error before redirecting to it::

from urllib.parse import urlsplit from django.urls import resolve from django.http import Http404, HttpResponseRedirect

def myview(request): next = request.META.get("HTTP_REFERER", None) or "/" response = HttpResponseRedirect(next)

# modify the request and response as required, e.g. change locale # and set corresponding locale cookie

view, args, kwargs = resolve(urlsplit(next).path) kwargs["request"] = request try: view(*args, **kwargs) except Http404: return HttpResponseRedirect("/") return response

`get_script_prefix()`

Normally, you should always use ~django.urls.reverse to define URLs within your application. However, if your application constructs part of the URL hierarchy itself, you may occasionally need to generate URLs. In that case, you need to be able to find the base URL of the Django project within its web server (normally, ~django.urls.reverse takes care of this for you). In that case, you can call `get_script_prefix(), which will return the script prefix portion of the URL for your Django project. If your Django project is at the root of its web server, this is always "/"`.

This function cannot be used outside of the request-response cycle since it relies on values initialized during that cycle.