如何在 Django 中重定向(包括 URL 更改)?
How to redirect (including URL change) in Django?
我创建了一个 index.html
。我希望在有人访问 http://www.mypage.com/
和 http://www.mypage.com/index/
时显示此页面(或 view
)。由于我是 Django
的新手,这可能是一个糟糕的方法:
在我的 URLS.PY:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.index),
url(r'^index/$',views.index),...
...
这工作正常,但我很好奇,当有人去 http://www.mypage.com/
时,是否可以将 url
从 http://www.mypage.com/
更改为 http://www.mypage.com/index/
。
我已经尝试过改变这个:
url(r'^$',views.index),
对此:
url(r'^$','/index/'),
但它引发错误:
Could not import '/index/'. The path must be fully qualified.
有人可以给我一些建议吗?
您可以执行以下操作。把这个放在你的 urls.py:
url(r'^$',views.redirect_index),
在您看来:
def redirect_index(request):
return redirect('index')
如果你想通过代码来完成它是:
from django.http import HttpResponseRedirect
def frontpage(request):
...
return HttpResponseRedirect('/index/')
不过你也可以直接在urls规则中做:
from django.views.generic import RedirectView
urlpatterns = patterns('',
(r'^$', RedirectView.as_view(url='/index/')),
)
作为参考,请参阅此 post:
我创建了一个 index.html
。我希望在有人访问 http://www.mypage.com/
和 http://www.mypage.com/index/
时显示此页面(或 view
)。由于我是 Django
的新手,这可能是一个糟糕的方法:
在我的 URLS.PY:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$',views.index),
url(r'^index/$',views.index),...
...
这工作正常,但我很好奇,当有人去 http://www.mypage.com/
时,是否可以将 url
从 http://www.mypage.com/
更改为 http://www.mypage.com/index/
。
我已经尝试过改变这个:
url(r'^$',views.index),
对此:
url(r'^$','/index/'),
但它引发错误:
Could not import '/index/'. The path must be fully qualified.
有人可以给我一些建议吗?
您可以执行以下操作。把这个放在你的 urls.py:
url(r'^$',views.redirect_index),
在您看来:
def redirect_index(request):
return redirect('index')
如果你想通过代码来完成它是:
from django.http import HttpResponseRedirect
def frontpage(request):
...
return HttpResponseRedirect('/index/')
不过你也可以直接在urls规则中做:
from django.views.generic import RedirectView
urlpatterns = patterns('',
(r'^$', RedirectView.as_view(url='/index/')),
)
作为参考,请参阅此 post: