页面重定向在Web应用程序有很多原因是必要的。您可能希望将用户重定向到另一个页面,当一个特定的动作发生,或者有错误的情况下。例如,当用户登录网站,他经常被重定向到他的主页或个人的仪表板。在Django中,定向使用“redirect”的方法来实现。
在“redirect”方法需要作为参数:URL要被重定向到的字符串的视图名字。
myapp/views 到现在为止如下所示 −
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.nhooo.com # Date : 2020-08-08 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将修改为如下:
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.nhooo.com # Date : 2020-08-08 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时−
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.nhooo.com # Date : 2020-08-08 url(r'^articles/(?P\d{2})/(?P\d{4})/', 'viewArticles', name = 'articles'),
该名称(这里的文章)可以被用作“redirect”方法的实参,那么 viewArticle 重定向可以修改 -
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.nhooo.com # Date : 2020-08-08 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")
修改为 −
# Filename : example.py # Copyright : 2020 By Nhooo # Author by : www.nhooo.com # Date : 2020-08-08 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和任何传入的参数编译视图的字符串。