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匯入重定向(redirect)。快捷方式並重定向到Django的官方網站上,我們只需使用完整URL到「redirect」方法作為字串,在第二例子(在viewArticle檢視)'redirect'方法取檢視名字和它的引數作為引數。
也可以指定「redirect」是否是暫時的還是永久性的,加入permanent = True引數。使用者看到不會有什麼區別,但這些都是細節,搜尋引擎網站排名時考慮到。
我們在url.py定義「name」引數在對映URL時?
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")
修改為 ?
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; 它是用在相同的方式重定向; 「reverse」方法(django.core.urlresolvers.reverse)。這個函式不返回HttpResponseRedirect物件,而僅僅包含URL和任何傳入的引數編譯檢視的字串。