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和任何传入的参数编译视图的字符串。