=================================``django.urls`` utility functions=================================.. module:: django.urls``reverse()``=============If you need to use something similar to the :ttag:`url` template tag inyour code, Django provides the following function:.. function:: reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)``viewname`` can be a :ref:`URL pattern name <naming-url-patterns>` or thecallable view object. For example, given the following ``url``::from news import viewspath('archive/', views.archive, name='news-archive')you can use any of the following to reverse the URL::# using the named URLreverse('news-archive')# passing a callable object# (This is discouraged because you can't reverse namespaced views this way.)from news import viewsreverse(views.archive)If the URL accepts arguments, you may pass them in ``args``. For example::from django.urls import reversedef myview(request):return HttpResponseRedirect(reverse('arch-summary', args=[1945]))You can also pass ``kwargs`` instead of ``args``. For example::>>> 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:class:`~django.urls.NoReverseMatch` exception.The ``reverse()`` function can reverse a large variety of regular expressionpatterns for URLs, but not every possible one. The main restriction at themoment is that the pattern cannot contain alternative choices using thevertical bar (``"|"``) character. You can quite happily use such patterns formatching against incoming URLs and sending them off to views, but you cannotreverse such patterns.The ``current_app`` argument allows you to provide a hint to the resolverindicating the application to which the currently executing view belongs.This ``current_app`` argument is used as a hint to resolve applicationnamespaces into URLs on specific application instances, according to the:ref:`namespaced URL resolution strategy <topics-http-reversing-url-namespaces>`.The ``urlconf`` argument is the URLconf module containing the URL patterns touse for reversing. By default, the root URLconf for the current thread is used... note::The string returned by ``reverse()`` is already:ref:`urlquoted <uri-and-iri-handling>`. For example::>>> reverse('cities', args=['Orléans'])'.../Orl%C3%A9ans/'Applying further encoding (such as :func:`urllib.parse.quote`) to the outputof ``reverse()`` may produce undesirable results.``reverse_lazy()``==================A lazily evaluated version of `reverse()`_... function:: reverse_lazy(viewname, urlconf=None, args=None, kwargs=None, current_app=None)It is useful for when you need to use a URL reversal before your project'sURLConf is loaded. Some common cases where this function is necessary are:* providing a reversed URL as the ``url`` attribute of a generic class-basedview.* providing a reversed URL to a decorator (such as the ``login_url`` argumentfor the :func:`django.contrib.auth.decorators.permission_required`decorator).* providing a reversed URL as a default value for a parameter in a function'ssignature.``resolve()``=============The ``resolve()`` function can be used for resolving URL paths to thecorresponding view functions. It has the following signature:.. function:: resolve(path, urlconf=None)``path`` is the URL path you want to resolve. As with:func:`~django.urls.reverse`, you don't need to worry about the ``urlconf``parameter. The function returns a :class:`ResolverMatch` object that allows youto access various metadata about the resolved URL.If the URL does not resolve, the function raises a:exc:`~django.urls.Resolver404` exception (a subclass of:class:`~django.http.Http404`) ... class:: ResolverMatch.. attribute:: ResolverMatch.funcThe view function that would be used to serve the URL.. attribute:: ResolverMatch.argsThe arguments that would be passed to the view function, asparsed from the URL... attribute:: ResolverMatch.kwargsAll 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.. versionadded:: 4.1The captured keyword arguments that would be passed to the viewfunction, as parsed from the URL... attribute:: ResolverMatch.extra_kwargs.. versionadded:: 4.1The additional keyword arguments that would be passed to the viewfunction... attribute:: ResolverMatch.url_nameThe name of the URL pattern that matches the URL... attribute:: ResolverMatch.routeThe route of the matching URL pattern.For example, if ``path('users/<id>/', ...)`` is the matching pattern,``route`` will contain ``'users/<id>/'``... attribute:: ResolverMatch.triedThe list of URL patterns tried before the URL either matched one orexhausted available patterns... attribute:: ResolverMatch.app_nameThe application namespace for the URL pattern that matches theURL... attribute:: ResolverMatch.app_namesThe list of individual namespace components in the fullapplication 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']``... attribute:: ResolverMatch.namespaceThe instance namespace for the URL pattern that matches theURL... attribute:: ResolverMatch.namespacesThe list of individual namespace components in the fullinstance namespace for the URL pattern that matches the URL.i.e., if the namespace is ``foo:bar``, then namespaces will be``['foo', 'bar']``... attribute:: ResolverMatch.view_nameThe name of the view that matches the URL, including the namespace ifthere is one.A :class:`ResolverMatch` object can then be interrogated to provideinformation about the URL pattern that matches a URL::# Resolve a URLmatch = resolve('/some/path/')# Print the URL pattern that matches the URLprint(match.url_name)A :class:`ResolverMatch` object can also be assigned to a triple::func, args, kwargs = resolve('/some/path/')One possible use of :func:`~django.urls.resolve` would be to test whether aview would raise a ``Http404`` error before redirecting to it::from urllib.parse import urlparsefrom django.urls import resolvefrom django.http import Http404, HttpResponseRedirectdef 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 cookieview, args, kwargs = resolve(urlparse(next)[2])kwargs['request'] = requesttry:view(*args, **kwargs)except Http404:return HttpResponseRedirect('/')return response``get_script_prefix()``=======================.. function:: get_script_prefix()Normally, you should always use :func:`~django.urls.reverse` to define URLswithin your application. However, if your application constructs part of theURL hierarchy itself, you may occasionally need to generate URLs. In thatcase, you need to be able to find the base URL of the Django project withinits web server (normally, :func:`~django.urls.reverse` takes care of this foryou). In that case, you can call ``get_script_prefix()``, which will returnthe script prefix portion of the URL for your Django project. If your Djangoproject is at the root of its web server, this is always ``"/"``.