直接从django中的urls.py重定向到命名的url模式? [英] Redirect to named url pattern directly from urls.py in django?
问题描述
在Django中,如何直接从urls.py执行简单的重定向?自然,我是一个组织良好的人,赞成DRY的原则,所以我想得到目标基于它的命名url模式,而不是硬编码url。
In Django, how can I do a simple redirect directly from urls.py? Naturally I am a well organized guy, favoring the DRY principle, so I would like to get the target based on it's named url pattern, rather than hard coding the url.
推荐答案
如果你在Django 1.4或1.5,你可以这样做:
If you are on Django 1.4 or 1.5, you can do this:
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView
urlpatterns = patterns('',
url(r'^some-page/$', RedirectView.as_view(url=reverse_lazy('my_named_pattern'), permanent=False)),
...
如果您使用的是Django 1.6或更高版本,可以执行以下操作:
If you are on Django 1.6 or above, you can do this:
from django.views.generic import RedirectView
urlpatterns = patterns('',
url(r'^some-page/$', RedirectView.as_view(pattern_name='my_named_pattern', permanent=False)),
...
在Django 1.9中,默认值 permanent
已更改fr因为这样,如果您没有指定
永久
关键字参数,您可能会看到此警告:
In Django 1.9, the default value of permanent
has changed from True to False. Because of this, if you don't specify the permanent
keyword argument, you may see this warning:
RemovedInDjango19警告:Django 1.9中的RedirectView.permanent的默认值将从True更改为False。设置一个显式值以使该警告静音。
RemovedInDjango19Warning: Default value of 'RedirectView.permanent' will change from True to False in Django 1.9. Set an explicit value to silence this warning.
这篇关于直接从django中的urls.py重定向到命名的url模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!