Django入门 专题
您的位置:python > Django入门 专题 > Django页面重定向
Django页面重定向
作者:--    发布时间:2019-11-20
页面重定向在web应用程序有很多原因是必要的。您可能希望将用户重定向到另一个页面,当一个特定的动作发生,或者有错误的情况下。例如,当用户登录网站,他经常被重定向到他的主页或个人的仪表板。在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导入重定向(redirect)。快捷方式并重定向到django的官方网站上,我们只需使用完整url到“redirect”方法作为字符串,在第二例子(在viewarticle视图)'redirect'方法取视图名字和它的参数作为参数。

访问/myapp/hello,会显示如下的屏幕-

并访问 /myapp/article/42,会给出下面的屏幕-

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



网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册