Django Reverse的使用

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) [source]

viewname can be a URL pattern name or thecallable 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 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.

更多关于Reverse的说明,参见django.urls utility functions:https://docs.djangoproject.com/en/1.10/ref/urlresolvers/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值