Python + Django page redirect

后端 未结 10 1862
别那么骄傲
别那么骄傲 2020-11-28 02:20

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

10条回答
  •  清歌不尽
    2020-11-28 02:49

    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.*)$', RedirectView.as_view(url='/new_path/%(path)s')),
    ]
    

    The ?P 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.

提交回复
热议问题