urls.reverse()

reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None) [source]

viewname can be a URL pattern name or the callable view object. For example, given the following url:

from news import views

url(r'^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:

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

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.

Note

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

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

Applying further encoding (such as urlquote() or urllib.quote) to the output of reverse() may produce undesirable results.

doc_Django
2016-10-09 18:40:17
Comments
Leave a Comment

Please login to continue.