django.urls utility functions

reverse()

If you need to use something similar to the url template tag inyour code, Django provides the following function:

  • reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)[源代码]
  • viewname can be a URL pattern name or thecallable view object. For example, given the following url:
  1. from news import views
  2.  
  3. path('archive/', views.archive, name='news-archive')

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

  1. # using the named URL
  2. reverse('news-archive')
  3.  
  4. # passing a callable object
  5. # (This is discouraged because you can't reverse namespaced views this way.)
  6. from news import views
  7. reverse(views.archive)

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

  1. from django.urls import reverse
  2.  
  3. def myview(request):
  4. return HttpResponseRedirect(reverse('arch-summary', args=[1945]))

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

  1. >>> reverse('admin:app_list', kwargs={'app_label': 'auth'})
  2. '/admin/auth/'

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

If no match can be made, reverse() raises aNoReverseMatch 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 thenamespaced URL resolution strategy.

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.

注解

The string returned by reverse() is alreadyurlquoted. For example:

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

Applying further encoding (such as urllib.parse.quote()) to the outputof reverse() may produce undesirable results.

reverse_lazy()

A lazily evaluated version of reverse().

  • reverselazy(_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 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:

  • resolve(path, urlconf=None)[源代码]
  • path is the URL path you want to resolve. As withreverse(), you don't need to worry about the urlconfparameter. The function returns a ResolverMatch object that allows youto access various metadata about the resolved URL.

If the URL does not resolve, the function raises aResolver404 exception (a subclass ofHttp404) .

  • class ResolverMatch[源代码]
    • func
    • The view function that would be used to serve the URL

    • args

    • The arguments that would be passed to the view function, asparsed from the URL.

    • kwargs

    • The keyword arguments that would be passed to the viewfunction, as parsed from the URL.

    • url_name

    • The name of the URL pattern that matches the URL.

    • route

    • New in Django 2.2:

The route of the matching URL pattern.

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

  • app_name
  • The application namespace for the URL pattern that matches theURL.

  • app_names

  • The 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_nameswill be ['foo', 'bar'].

  • namespace

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

  • namespaces

  • The 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'].

  • view_name

  • The name of the view that matches the URL, including the namespace ifthere is one.

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

  1. # Resolve a URL
  2. match = resolve('/some/path/')
  3. # Print the URL pattern that matches the URL
  4. print(match.url_name)

A ResolverMatch object can also be assigned to a triple:

  1. func, args, kwargs = resolve('/some/path/')

One possible use of resolve() would be to test whether aview would raise a Http404 error before redirecting to it:

  1. from urllib.parse import urlparse
  2. from django.urls import resolve
  3. from django.http import Http404, HttpResponseRedirect
  4.  
  5. def myview(request):
  6. next = request.META.get('HTTP_REFERER', None) or '/'
  7. response = HttpResponseRedirect(next)
  8.  
  9. # modify the request and response as required, e.g. change locale
  10. # and set corresponding locale cookie
  11.  
  12. view, args, kwargs = resolve(urlparse(next)[2])
  13. kwargs['request'] = request
  14. try:
  15. view(*args, **kwargs)
  16. except Http404:
  17. return HttpResponseRedirect('/')
  18. return response

get_script_prefix()

  • get_script_prefix()[源代码]
  • Normally, you should always use 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, 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 "/".