教程 > django 教程 > 阅读:165

django 页面重定向——迹忆客-ag捕鱼王app官网

在 web 应用程序中,出于很多原因需要页面重定向。我们可能希望在发生特定操作时或者在发生错误时将用户重定向到另一个页面。例如,当用户登录我们的网站时,他通常会被重定向到ag捕鱼王app官网主页或他的个人中心。在 django 中,重定向是使用 'redirect' 方法完成的。

'redirect' 方法接受以下参数: 希望作为字符串重定向到的 url 视图的名称。

在前面几节,我们在 app/views.py 定义了下面几个视图

from django.http import httpresponse
def hello(request):
    text = "

这是 app 应用中的视图

" return httpresponse(text) def article(request, articlenumber): text = "

你现在访问的文章编号为:%s

" % articlenumber return httpresponse(text) def articles(request, year, month): text = "

获取 %s/%s 的文章

" % (year, month) return httpresponse(text)

现在我们修改 hello 视图,使其重定向到本站的ag捕鱼王app官网主页 jiyik.com。 然后修改article视图,使其重定向到我们的 /app/articles 页面。

首先我们来修改 hello 视图

def hello(request):
    text = "

这是 app 应用中的视图

" return redirect("https://www.jiyik.com")

然后我们重启服务,在浏览器中访问 /app/hello,会看到页面会被重定向到本站的ag捕鱼王app官网主页。

django 重定向跳转到迹忆客ag捕鱼王app官网主页

下面我们修改 article 视图

def article(request, articlenumber):
    text = "

你现在访问的文章编号为:%s

" % articlenumber return redirect(articles, year="2045", month="02")

将其重定向到 articles 视图。这里要注意articles视图中的参数。我们再来重温一下 articles路由的定义

re_path(r'articles/(?p\d{2})/(?p\d{4})', views.articles),

然后重启服务,在浏览器中访问 /app/article/12 会看到页面会被重定向到 /app/articles/02/2045

django 重定向到视图

我们还可以通过添加 permanent = true 参数来指定“重定向”是临时的还是永久的。虽然这些对用户来说看不出什么区别,但是这对搜索引擎来说是很重要的,它会影响搜索引擎对我们的网站的排名。

现在我们查看一下重定向的状态码,发现是 302,这时一种临时跳转。 对于 http 协议不是很清楚的可以查看我们的 http教程

django 临时重定向状态码302

然后我们在 article视图中的 redirect 函数中加上 permanent = true 参数

def article(request, articlenumber):
    text = "

你现在访问的文章编号为:%s

" % articlenumber return redirect(articles, year="2045", month="02", permanent=true)

注意: permanent 是小写,而不能是 permanent

现在我们再次查看重定向的状态码,已经是301 永久重定向了。

django 页面永久重定向301

reverse

django 还提供了一个生成 url 的功能;它的使用方式与 redirect 相同;reverse 方法(django.core.urlresolvers.reverse)。此函数不返回 httpresponseredirect 对象,而只是返回一个字符串,其中包含使用任何传递的参数编译的视图的 url。

下面我们修改 article 视图,使用 reverse 函数转换 articles视图为 url。

def article(request, articlenumber):
    text = "

你现在访问的文章编号为:%s

" % articlenumber return httpresponseredirect(reverse(articles, kwargs={"year": "2045", "month": "02"}))

同样可以将 /app/article/12 重定向到 /app/articles/02/2045

查看笔记

扫码一下
查看教程更方便
网站地图