Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
Django

The web framework for perfectionists with deadlines.

Documentation

django.urls utility functions

Deprecated since version 1.10:In older versions, these functions are located indjango.core.urlresolvers. Importing from the old location will continueto work until Django 2.0.

reverse()

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

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

viewname can be aURL pattern name or thecallable view object. For example, given the followingurl:

fromnewsimportviewsurl(r'^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.)fromnewsimportviewsreverse(views.archive)

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

fromdjango.urlsimportreversedefmyview(request):returnHttpResponseRedirect(reverse('arch-summary',args=[1945]))

You can also passkwargs instead ofargs. For example:

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

args andkwargs cannot be passed toreverse() at the same time.

If no match can be made,reverse() raises aNoReverseMatch exception.

Thereverse() 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.

Thecurrent_app argument allows you to provide a hint to the resolverindicating the application to which the currently executing view belongs.Thiscurrent_app argument is used as a hint to resolve applicationnamespaces into URLs on specific application instances, according to thenamespaced URL resolution strategy.

Theurlconf 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 byreverse() is alreadyurlquoted. For example:

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

Applying further encoding (such asurlquote() orurllib.quote) to the output ofreverse() may produce undesirableresults.

reverse_lazy()

A lazily evaluated version ofreverse().

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 theurl attribute of a generic class-basedview.
  • providing a reversed URL to a decorator (such as thelogin_url argumentfor thedjango.contrib.auth.decorators.permission_required()decorator).
  • providing a reversed URL as a default value for a parameter in a function’ssignature.

resolve()

Theresolve() function can be used for resolving URL paths to thecorresponding view functions. It has the following signature:

resolve(path,urlconf=None)[source]

path is the URL path you want to resolve. As withreverse(), you don’t need to worry about theurlconfparameter. The function returns aResolverMatch 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) .

classResolverMatch[source]
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.

app_name

The application namespace for the URL pattern that matches theURL.

app_names
New in Django 1.9.

The list of individual namespace components in the fullapplication namespace for the URL pattern that matches the URL.For example, if theapp_name is'foo:bar', thenapp_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 isfoo:bar, then namespaces will be['foo','bar'].

view_name

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

AResolverMatch 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)

AResolverMatch object can also be assigned to a triple:

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

One possible use ofresolve() would be to test whether aview would raise aHttp404 error before redirecting to it:

fromdjango.urlsimportresolvefromdjango.httpimportHttpResponseRedirect,Http404fromdjango.utils.six.moves.urllib.parseimporturlparsedefmyview(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)exceptHttp404:returnHttpResponseRedirect('/')returnresponse

get_script_prefix()

get_script_prefix()[source]

Normally, you should always usereverse() 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 callget_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"/".

Back to Top

Additional Information

Support Django!

Support Django!

Contents

Getting help

FAQ
Try the FAQ — it's got answers to many common questions.
Index,Module Index, orTable of Contents
Handy when looking for specific information.
Django Discord Server
Join the Django Discord Community.
Official Django Forum
Join the community on the Django Forum.
Ticket tracker
Report bugs with Django or Django documentation in our ticket tracker.

Download:

Offline (Django 1.10):HTML |PDF |ePub
Provided byRead the Docs.

Diamond and Platinum Members

Sentry
JetBrains
This document is for an insecure version of Django that is no longer supported. Please upgrade to a newer release!

[8]ページ先頭

©2009-2025 Movatter.jp