Python + Django页面重定向

问题:Python + Django页面重定向

如何在Django中完成简单的重定向(例如,cflocation在ColdFusion中或header(location:http://)对于PHP)?

How do I accomplish a simple redirect (e.g. cflocation in ColdFusion, or header(location:http://) for PHP) in Django?


回答 0

这很简单:

from django.http import HttpResponseRedirect

def myview(request):
    ...
    return HttpResponseRedirect("/path/")

官方Django文档中的更多信息

更新:Django 1.0

显然,现在使用,在Django中有一种更好的方法generic views

范例-

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',   
    (r'^one/$', redirect_to, {'url': '/another/'}),

    #etc...
)

通用视图文档中还有更多内容。信贷银行的Barrobés

更新#2:Django 1.3+

在Django 1.5中,redirect_to不再存在,并已由RedirectView代替。感谢Yonatan

from django.views.generic import RedirectView

urlpatterns = patterns('',
    (r'^one/$', RedirectView.as_view(url='/another/')),
)

It’s simple:

from django.http import HttpResponseRedirect

def myview(request):
    ...
    return HttpResponseRedirect("/path/")

More info in the official Django docs

Update: Django 1.0

There is apparently a better way of doing this in Django now using generic views.

Example –

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',   
    (r'^one/$', redirect_to, {'url': '/another/'}),

    #etc...
)

There is more in the generic views documentation. Credit – Carles Barrobés.

Update #2: Django 1.3+

In Django 1.5 redirect_to no longer exists and has been replaced by RedirectView. Credit to Yonatan

from django.views.generic import RedirectView

urlpatterns = patterns('',
    (r'^one/$', RedirectView.as_view(url='/another/')),
)

回答 1

根据您的需要(即,如果您不想进行任何其他预处理),仅使用Django的redirect_to通用视图会更简单:

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',
    (r'^one/$', redirect_to, {'url': '/another/'}),

    #etc...
)

有关更多高级示例,请参见文档


对于Django 1.3+,请使用:

from django.views.generic import RedirectView

urlpatterns = patterns('',
    (r'^one/$', RedirectView.as_view(url='/another/')),
)

Depending on what you want (i.e. if you do not want to do any additional pre-processing), it is simpler to just use Django’s redirect_to generic view:

from django.views.generic.simple import redirect_to

urlpatterns = patterns('',
    (r'^one/$', redirect_to, {'url': '/another/'}),

    #etc...
)

See documentation for more advanced examples.


For Django 1.3+ use:

from django.views.generic import RedirectView

urlpatterns = patterns('',
    (r'^one/$', RedirectView.as_view(url='/another/')),
)

回答 2

实际上,有一个比为每个重定向查看都有更简单的方法-您可以直接在中执行此操作urls.py

from django.http import HttpResponsePermanentRedirect

urlpatterns = patterns(
    '',
    # ...normal patterns here...
    (r'^bad-old-link\.php',
     lambda request: HttpResponsePermanentRedirect('/nice-link')),
)

目标既可以是可调用的,也可以是字符串,这是我在这里使用的。

There’s actually a simpler way than having a view for each redirect – you can do it directly in urls.py:

from django.http import HttpResponsePermanentRedirect

urlpatterns = patterns(
    '',
    # ...normal patterns here...
    (r'^bad-old-link\.php',
     lambda request: HttpResponsePermanentRedirect('/nice-link')),
)

A target can be a callable as well as a string, which is what I’m using here.


回答 3

从Django 1.1开始,您还可以使用更简单的重定向快捷方式:

from django.shortcuts import redirect

def myview(request):
    return redirect('/path')

它还需要一个可选的persistent = True关键字参数。

Since Django 1.1, you can also use the simpler redirect shortcut:

from django.shortcuts import redirect

def myview(request):
    return redirect('/path')

It also takes an optional permanent=True keyword argument.


回答 4

如果您想重定向整个子文件夹,那么RedirectView中url参数实际上是插值的,因此您可以在以下代码中执行以下操作urls.py

from django.conf.urls.defaults import url
from django.views.generic import RedirectView

urlpatterns = [
    url(r'^old/(?P<path>.*)$', RedirectView.as_view(url='/new_path/%(path)s')),
]

?P<path>您捕捉将被送入RedirectView。然后,该捕获的变量将替换为url您提供的参数,/new_path/yay/mypath如果您的原始路径为,则会给我们/old/yay/mypath

….as_view(url='…', query_string=True)如果您也想复制查询字符串,也可以这样做。

If you want to redirect a whole subfolder, the url argument in RedirectView is actually interpolated, so you can do something like this in urls.py:

from django.conf.urls.defaults import url
from django.views.generic import RedirectView

urlpatterns = [
    url(r'^old/(?P<path>.*)$', RedirectView.as_view(url='/new_path/%(path)s')),
]

The ?P<path> you capture will be fed into RedirectView. This captured variable will then be replaced in the url argument you gave, giving us /new_path/yay/mypath if your original path was /old/yay/mypath.

You can also do ….as_view(url='…', query_string=True) if you want to copy the query string over as well.


回答 5

在Django 1.3版中,基于类的方法是:

from django.conf.urls.defaults import patterns, url
from django.views.generic import RedirectView

urlpatterns = patterns('',
    url(r'^some-url/$', RedirectView.as_view(url='/redirect-url/'), name='some_redirect'),
)

此示例位于urls.py中

With Django version 1.3, the class based approach is:

from django.conf.urls.defaults import patterns, url
from django.views.generic import RedirectView

urlpatterns = patterns('',
    url(r'^some-url/$', RedirectView.as_view(url='/redirect-url/'), name='some_redirect'),
)

This example lives in in urls.py


回答 6

谨防。我在开发服务器上进行了此操作,并希望稍后进行更改。

我必须清除缓存以进行更改。为了避免将来出现这种令人头疼的问题,我可以将其设置为临时状态,如下所示:

from django.views.generic import RedirectView

url(r'^source$', RedirectView.as_view(permanent=False, 
                                      url='/dest/')),

Beware. I did this on a development server and wanted to change it later.

I had to clear my caches to change it. In order to avoid this head-scratching in the future, I was able to make it temporary like so:

from django.views.generic import RedirectView

url(r'^source$', RedirectView.as_view(permanent=False, 
                                      url='/dest/')),

回答 7

您可以在“管理员”部分中执行此操作。在文档中对其进行了说明。

https://docs.djangoproject.com/en/dev/ref/contrib/redirects/

You can do this in the Admin section. It’s explained in the documentation.

https://docs.djangoproject.com/en/dev/ref/contrib/redirects/


回答 8

page_path =在urls.py中定义

def deletePolls(request):
    pollId = deletePool(request.GET['id'])
    return HttpResponseRedirect("/page_path/")

page_path = define in urls.py

def deletePolls(request):
    pollId = deletePool(request.GET['id'])
    return HttpResponseRedirect("/page_path/")

回答 9

这应该在大多数版本的Django中都可以使用,我在1.6.5中使用了它:

from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
urlpatterns = patterns('',
    ....
    url(r'^(?P<location_id>\d+)/$', lambda x, location_id: HttpResponseRedirect(reverse('dailyreport_location', args=[location_id])), name='location_stats_redirect'),
    ....
)

使用此解决方案,您仍然可以使用url模式的名称,而不是硬编码的url。网址中的location_id参数向下传递给lambda函数。

This should work in most versions of django, I am using it in 1.6.5:

from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
urlpatterns = patterns('',
    ....
    url(r'^(?P<location_id>\d+)/$', lambda x, location_id: HttpResponseRedirect(reverse('dailyreport_location', args=[location_id])), name='location_stats_redirect'),
    ....
)

You can still use the name of the url pattern instead of a hard coded url with this solution. The location_id parameter from the url is passed down to the lambda function.