Django 页面重定向
网页应用中经常需要进行页面重定向。在特定操作发生时,你可能想要将用户重定向到另一个页面,或者在出错时进行重定向。例如,当用户登录到你的网站时,通常会将他重定向到主页或个人仪表盘。在Django中,可以使用’redirect’方法来进行重定向。
‘redirect’方法的参数为:作为字符串的要重定向到的URL,一个视图的名称。
目前myapp/views的代码如下−
def hello(request):
today = datetime.datetime.now().date()
daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
return render(request, "hello.html", {"today" : today, "days_of_week" : daysOfWeek})
def viewArticle(request, articleId):
""" A view that display an article based on his ID"""
text = "Displaying article Number : %s" %articleId
return HttpResponse(text)
def viewArticles(request, year, month):
text = "Displaying articles of : %s/%s"%(year, month)
return HttpResponse(text)
让我们将hello视图改为重定向到djangoproject.com,将viewArticle重定向到我们的内部’/myapp/articles’。为此,myapp/view.py将会改变为−
from django.shortcuts import render, redirect
from django.http import HttpResponse
import datetime
# Create your views here.
def hello(request):
today = datetime.datetime.now().date()
daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
return redirect("https://www.djangoproject.com")
def viewArticle(request, articleId):
""" A view that display an article based on his ID"""
text = "Displaying article Number : %s" %articleId
return redirect(viewArticles, year = "2045", month = "02")
def viewArticles(request, year, month):
text = "Displaying articles of : %s/%s"%(year, month)
return HttpResponse(text)
在上面的例子中,首先我们从django.shortcuts中导入了redirect,并且为了将页面重定向到Django官方网站,我们只需要将完整的URL作为字符串传递给’redirect’方法。而对于第二个例子(viewArticle视图),’redirect’方法将视图名称和其参数作为参数。
访问/myapp/hello,将会显示以下页面 −
访问/myapp/article/42,你将看到如下屏幕 −
还可以通过添加permanent=True参数来指定“redirect”是临时还是永久的。用户看不出任何区别,但这些是搜索引擎在排名您的网站时考虑的细节。
还要记住,在我们的url.py中映射URL时定义的“name”参数-
url(r'^articles/(?P\d{2})/(?P\d{4})/', 'viewArticles', name = 'articles'),
那个名称(这里是文章)可以作为’redirect’方法的参数使用,然后我们的viewArticle重定向可以改为-
def viewArticle(request, articleId):
""" A view that display an article based on his ID"""
text = "Displaying article Number : %s" %articleId
return redirect(viewArticles, year = "2045", month = "02")
To −
def viewArticle(request, articleId):
""" A view that display an article based on his ID"""
text = "Displaying article Number : %s" %articleId
return redirect(articles, year = "2045", month = "02")
注意 - 还有一个生成URL的函数;使用方法与redirect相同;该函数称为’reverse’方法(django.core.urlresolvers.reverse)。 这个函数不返回HttpRedirect对象,而是返回一个包含编译视图与任何传递参数的URL的字符串。