HttpResponseRedirect实现重定向

HttpResponseRedirect类是HttpResponse类的子类,HttpResponseRedirect类接收的响应信息是URL。创建HttpResponseRedirect对象时必须将用来重定向的URL作为第一个参数传递给构造方法,这个URL可以是完整的链接(如http://example.com/),也可以是不包含域名的绝对路径(如/example/)或相对路径(如example/)。

示例代码如下:
return HttpResponseRedirect("http://example.com/")	# 链接
return HttpResponseRedirect("/example")				# 绝对路径
return HttpResponseRedirect("example/")				# 相对路径

需要注意的是,HttpResponseRedirect只支持硬编码链接,不能直接使用URL名称,若要使用URL名称,需要先使用反向解析方法reverse()解析URL。

示例代码如下:
def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    context = {
    
    
        'question': question,
        'error_message': "You didn't select a choice.",
    }
    try:
        selected_choice = question.choice_set.get(pk=request.POST['choice'])  # request.POST 是一个类字典对象,让你可以通过关键字的名字获取提交的数据。这里是以字符串形式返回选择的 Choice 的 ID
    except(KeyError, Choice.DoesNotExist):
        # Redisplay the question voting form.
        return render(request, 'hello/vote.html', context)
    else:
        selected_choice.votes += 1
        selected_choice.save()
        return http.HttpResponseRedirect(reverse('hello:results', args=(question.id,)))

示例中最后一行重定向到投票结果的模板,使用reverse()函数避免了我们在视图函数中硬编码 URL。它需要我们给出我们想要跳转的视图的名字和该视图所对应的 URL 模式中需要给该视图提供的参数
reverse() 调用将返回一个这样的字符串:‘/hello/2/results’

HttpResponseRedirect默认返回302状态码和临时重定向,可以传入命名参数status重设状态码、设置参数permanent值为True以返回永久重定向。使用类HttpResponsePermanentRedirect可直接返回永久重定向(状态码为301)

猜你喜欢

转载自blog.csdn.net/m0_53195006/article/details/123756902
今日推荐