myapp/views 到現(xiàn)在為止如下所示 ?
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 重定向到我們內(nèi)部的 '/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導(dǎo)入重定向(redirect)。快捷方式并重定向到Django的官方網(wǎng)站上,我們只需使用完整URL到“redirect”方法作為字符串,在第二例子(在viewArticle視圖)'redirect'方法取視圖名字和它的參數(shù)作為參數(shù)。
也可以指定“redirect”是否是暫時(shí)的還是永久性的,加入permanent = True參數(shù)。用戶看到不會(huì)有什么區(qū)別,但這些都是細(xì)節(jié),搜索引擎網(wǎng)站排名時(shí)考慮到。
我們?cè)趗rl.py定義“name”參數(shù)在映射URL時(shí)?
url(r'^articles/(?P\d{2})/(?P\d{4})/', 'viewArticles', name = 'articles'),
該名稱(這里的文章)可以被用作“redirect”方法的實(shí)參,那么 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")
注 - 還有一個(gè)函數(shù)生成 URL; 它是用在相同的方式重定向; “reverse”方法(django.core.urlresolvers.reverse)。這個(gè)函數(shù)不返回HttpResponseRedirect對(duì)象,而僅僅包含URL和任何傳入的參數(shù)編譯視圖的字符串。