- Django基础
- Django开发环境安装配置
- Django创建工程
- Django生命周期
- Django管理员界面
- Django创建视图
- Django URL映射
- Django模板系统
- Django模型
- Django页面重定向
- Django发送E-mail
- Django通用视图
- Django表单处理
- Django上传文件
- Django Apache配置
- Django Cookies处理
- Django Session会话
- Django缓存
- Django RSS
- Django Ajax应用
- Django快速入门
- Django快速入门-数据库模型
- Django快速入门-视图
- Django快速入门-表单
Django页面重定向
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和任何传入的参数编译视图的字符串。
上一篇:Django模型
下一篇:Django发送E-mail
扫描二维码
程序员编程王