2015-12-30 15:51:16 +00:00
|
|
|
=================================
|
|
|
|
``django.urls`` utility functions
|
|
|
|
=================================
|
2012-09-27 22:16:49 +00:00
|
|
|
|
2015-12-30 15:51:16 +00:00
|
|
|
.. module:: django.urls
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``reverse()``
|
|
|
|
=============
|
2012-09-27 22:16:49 +00:00
|
|
|
|
|
|
|
If you need to use something similar to the :ttag:`url` template tag in
|
2012-10-07 23:11:12 +00:00
|
|
|
your code, Django provides the following function:
|
2012-09-27 22:16:49 +00:00
|
|
|
|
2015-07-27 12:35:21 +00:00
|
|
|
.. function:: reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)
|
2012-09-27 22:16:49 +00:00
|
|
|
|
2015-08-17 17:45:07 +00:00
|
|
|
``viewname`` can be a :ref:`URL pattern name <naming-url-patterns>` or the
|
2024-10-22 12:12:02 +00:00
|
|
|
callable view object used in the URLconf. For example, given the following
|
|
|
|
``url``::
|
2014-04-14 17:09:17 +00:00
|
|
|
|
2014-06-03 11:30:14 +00:00
|
|
|
from news import views
|
2014-04-14 17:09:17 +00:00
|
|
|
|
2016-10-20 17:29:04 +00:00
|
|
|
path("archive/", views.archive, name="news-archive")
|
2014-04-14 17:09:17 +00:00
|
|
|
|
2014-06-03 11:30:14 +00:00
|
|
|
you can use any of the following to reverse the URL::
|
2014-04-14 17:09:17 +00:00
|
|
|
|
|
|
|
# using the named URL
|
2015-11-07 14:50:43 +00:00
|
|
|
reverse("news-archive")
|
2014-04-14 17:09:17 +00:00
|
|
|
|
|
|
|
# passing a callable object
|
2015-08-03 12:33:51 +00:00
|
|
|
# (This is discouraged because you can't reverse namespaced views this way.)
|
2014-04-14 17:09:17 +00:00
|
|
|
from news import views
|
2023-02-28 19:53:28 +00:00
|
|
|
|
2014-04-14 17:09:17 +00:00
|
|
|
reverse(views.archive)
|
|
|
|
|
|
|
|
If the URL accepts arguments, you may pass them in ``args``. For example::
|
2012-09-27 22:16:49 +00:00
|
|
|
|
2015-12-30 15:51:16 +00:00
|
|
|
from django.urls import reverse
|
2012-09-27 22:16:49 +00:00
|
|
|
|
2023-02-28 19:53:28 +00:00
|
|
|
|
2012-09-27 22:16:49 +00:00
|
|
|
def myview(request):
|
|
|
|
return HttpResponseRedirect(reverse("arch-summary", args=[1945]))
|
|
|
|
|
2014-04-14 17:09:17 +00:00
|
|
|
You can also pass ``kwargs`` instead of ``args``. For example:
|
2023-02-09 15:48:46 +00:00
|
|
|
|
2014-04-14 17:09:17 +00:00
|
|
|
.. code-block:: pycon
|
|
|
|
|
|
|
|
>>> reverse("admin:app_list", kwargs={"app_label": "auth"})
|
|
|
|
'/admin/auth/'
|
|
|
|
|
|
|
|
``args`` and ``kwargs`` cannot be passed to ``reverse()`` at the same time.
|
|
|
|
|
2014-02-23 12:21:09 +00:00
|
|
|
If no match can be made, ``reverse()`` raises a
|
2015-12-30 15:51:16 +00:00
|
|
|
:class:`~django.urls.NoReverseMatch` exception.
|
2014-02-23 12:21:09 +00:00
|
|
|
|
2012-09-27 22:16:49 +00:00
|
|
|
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
|
|
|
|
:ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`.
|
|
|
|
|
2016-07-06 19:31:12 +00:00
|
|
|
The ``urlconf`` argument is the URLconf module containing the URL patterns to
|
2014-04-14 17:09:17 +00:00
|
|
|
use for reversing. By default, the root URLconf for the current thread is used.
|
2012-09-27 22:16:49 +00:00
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
2012-10-07 23:11:12 +00:00
|
|
|
The string returned by ``reverse()`` is already
|
2012-09-27 22:16:49 +00:00
|
|
|
:ref:`urlquoted <uri-and-iri-handling>`. For example:
|
2023-02-09 15:48:46 +00:00
|
|
|
|
2012-09-27 22:16:49 +00:00
|
|
|
.. code-block:: pycon
|
|
|
|
|
2014-03-22 20:30:49 +00:00
|
|
|
>>> reverse("cities", args=["Orléans"])
|
2012-09-27 22:16:49 +00:00
|
|
|
'.../Orl%C3%A9ans/'
|
|
|
|
|
2017-01-26 13:25:15 +00:00
|
|
|
Applying further encoding (such as :func:`urllib.parse.quote`) to the output
|
|
|
|
of ``reverse()`` may produce undesirable results.
|
2012-09-27 22:16:49 +00:00
|
|
|
|
2024-10-22 12:12:02 +00:00
|
|
|
.. admonition:: Reversing class-based views by view object
|
|
|
|
|
|
|
|
The view object can also be the result of calling
|
|
|
|
:meth:`~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:
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
:caption: ``news/views.py``
|
|
|
|
|
|
|
|
from django.views import View
|
|
|
|
|
|
|
|
|
|
|
|
class ArchiveView(View): ...
|
|
|
|
|
|
|
|
|
|
|
|
archive = ArchiveView.as_view()
|
|
|
|
|
|
|
|
However, remember that namespaced views cannot be reversed by view object.
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``reverse_lazy()``
|
|
|
|
==================
|
2012-09-27 22:16:49 +00:00
|
|
|
|
|
|
|
A lazily evaluated version of `reverse()`_.
|
|
|
|
|
2015-07-27 12:35:21 +00:00
|
|
|
.. function:: reverse_lazy(viewname, urlconf=None, args=None, kwargs=None, current_app=None)
|
2012-09-27 22:16:49 +00:00
|
|
|
|
|
|
|
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 :func:`django.contrib.auth.decorators.permission_required`
|
|
|
|
decorator).
|
|
|
|
|
|
|
|
* providing a reversed URL as a default value for a parameter in a function's
|
|
|
|
signature.
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``resolve()``
|
|
|
|
=============
|
2012-09-27 22:16:49 +00:00
|
|
|
|
2012-10-07 23:11:12 +00:00
|
|
|
The ``resolve()`` function can be used for resolving URL paths to the
|
|
|
|
corresponding view functions. It has the following signature:
|
2012-09-27 22:16:49 +00:00
|
|
|
|
|
|
|
.. function:: resolve(path, urlconf=None)
|
|
|
|
|
|
|
|
``path`` is the URL path you want to resolve. As with
|
2015-12-30 15:51:16 +00:00
|
|
|
:func:`~django.urls.reverse`, you don't need to worry about the ``urlconf``
|
|
|
|
parameter. The function returns a :class:`ResolverMatch` object that allows you
|
|
|
|
to access various metadata about the resolved URL.
|
2012-09-27 22:16:49 +00:00
|
|
|
|
2013-09-05 12:43:10 +00:00
|
|
|
If the URL does not resolve, the function raises a
|
2015-12-30 15:51:16 +00:00
|
|
|
:exc:`~django.urls.Resolver404` exception (a subclass of
|
2013-09-05 12:43:10 +00:00
|
|
|
:class:`~django.http.Http404`) .
|
2012-09-27 22:16:49 +00:00
|
|
|
|
|
|
|
.. class:: ResolverMatch
|
|
|
|
|
|
|
|
.. attribute:: ResolverMatch.func
|
|
|
|
|
|
|
|
The view function that would be used to serve the URL
|
|
|
|
|
|
|
|
.. attribute:: ResolverMatch.args
|
|
|
|
|
|
|
|
The arguments that would be passed to the view function, as
|
|
|
|
parsed from the URL.
|
|
|
|
|
|
|
|
.. attribute:: ResolverMatch.kwargs
|
|
|
|
|
2022-03-28 15:56:20 +00:00
|
|
|
All keyword arguments that would be passed to the view function, i.e.
|
|
|
|
:attr:`~ResolverMatch.captured_kwargs` and
|
|
|
|
:attr:`~ResolverMatch.extra_kwargs`.
|
|
|
|
|
|
|
|
.. attribute:: ResolverMatch.captured_kwargs
|
|
|
|
|
|
|
|
The captured keyword arguments that would be passed to the view
|
2012-09-27 22:16:49 +00:00
|
|
|
function, as parsed from the URL.
|
|
|
|
|
2022-03-28 15:56:20 +00:00
|
|
|
.. attribute:: ResolverMatch.extra_kwargs
|
|
|
|
|
|
|
|
The additional keyword arguments that would be passed to the view
|
|
|
|
function.
|
|
|
|
|
2012-09-27 22:16:49 +00:00
|
|
|
.. attribute:: ResolverMatch.url_name
|
|
|
|
|
|
|
|
The name of the URL pattern that matches the URL.
|
|
|
|
|
2017-11-02 16:35:41 +00:00
|
|
|
.. attribute:: ResolverMatch.route
|
|
|
|
|
|
|
|
The route of the matching URL pattern.
|
|
|
|
|
|
|
|
For example, if ``path('users/<id>/', ...)`` is the matching pattern,
|
|
|
|
``route`` will contain ``'users/<id>/'``.
|
|
|
|
|
2020-07-07 23:23:54 +00:00
|
|
|
.. attribute:: ResolverMatch.tried
|
|
|
|
|
|
|
|
The list of URL patterns tried before the URL either matched one or
|
|
|
|
exhausted available patterns.
|
|
|
|
|
2012-09-27 22:16:49 +00:00
|
|
|
.. attribute:: ResolverMatch.app_name
|
|
|
|
|
|
|
|
The application namespace for the URL pattern that matches the
|
|
|
|
URL.
|
|
|
|
|
2015-06-03 17:12:27 +00:00
|
|
|
.. attribute:: ResolverMatch.app_names
|
|
|
|
|
|
|
|
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']``.
|
|
|
|
|
2012-09-27 22:16:49 +00:00
|
|
|
.. attribute:: ResolverMatch.namespace
|
|
|
|
|
|
|
|
The instance namespace for the URL pattern that matches the
|
|
|
|
URL.
|
|
|
|
|
|
|
|
.. attribute:: ResolverMatch.namespaces
|
|
|
|
|
|
|
|
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']``.
|
|
|
|
|
2014-02-22 15:25:49 +00:00
|
|
|
.. attribute:: ResolverMatch.view_name
|
|
|
|
|
|
|
|
The name of the view that matches the URL, including the namespace if
|
|
|
|
there is one.
|
|
|
|
|
2012-09-27 22:16:49 +00:00
|
|
|
A :class:`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 :class:`ResolverMatch` object can also be assigned to a triple::
|
|
|
|
|
|
|
|
func, args, kwargs = resolve("/some/path/")
|
|
|
|
|
2015-12-30 15:51:16 +00:00
|
|
|
One possible use of :func:`~django.urls.resolve` would be to test whether a
|
|
|
|
view would raise a ``Http404`` error before redirecting to it::
|
2012-09-27 22:16:49 +00:00
|
|
|
|
2024-05-29 13:48:27 +00:00
|
|
|
from urllib.parse import urlsplit
|
2015-12-30 15:51:16 +00:00
|
|
|
from django.urls import resolve
|
2018-05-12 17:37:42 +00:00
|
|
|
from django.http import Http404, HttpResponseRedirect
|
2012-09-27 22:16:49 +00:00
|
|
|
|
2023-02-28 19:53:28 +00:00
|
|
|
|
2012-09-27 22:16:49 +00:00
|
|
|
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
|
|
|
|
|
2024-05-29 13:48:27 +00:00
|
|
|
view, args, kwargs = resolve(urlsplit(next).path)
|
2012-09-27 22:16:49 +00:00
|
|
|
kwargs["request"] = request
|
|
|
|
try:
|
|
|
|
view(*args, **kwargs)
|
|
|
|
except Http404:
|
|
|
|
return HttpResponseRedirect("/")
|
|
|
|
return response
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``get_script_prefix()``
|
|
|
|
=======================
|
2012-09-27 22:16:49 +00:00
|
|
|
|
|
|
|
.. function:: get_script_prefix()
|
|
|
|
|
2015-12-30 15:51:16 +00:00
|
|
|
Normally, you should always use :func:`~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
|
2021-07-23 06:48:16 +00:00
|
|
|
its web server (normally, :func:`~django.urls.reverse` takes care of this for
|
2015-12-30 15:51:16 +00:00
|
|
|
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 ``"/"``.
|
2023-04-06 11:01:26 +00:00
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
|
|
|
This function **cannot** be used outside of the request-response cycle
|
|
|
|
since it relies on values initialized during that cycle.
|