Django:HttpResponseRedirect不通过RequestContext()? [英] Django: HttpResponseRedirect doesnt pass RequestContext()?

查看:124
本文介绍了Django:HttpResponseRedirect不通过RequestContext()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用的是:

基本上,我正在尝试将未登录的用户重定向到登录页面。

What I'm currently using is:

return render_to_response('login.html', context_instance=RequestContext(request))

但是,在主页上留下网址。我想要重定向到/ accounts / login /,但是当我使用

But that leaves the url at the homepage. I'd like to have it redirect to /accounts/login/, but when I use

return HttpResponseRedirect('/accounts/login/')

我收到错误

Key 'username' not found in <QueryDict: {}>

我明白,这意味着我需要有

I understand that to mean that I do need to have

context_instance=RequestContext(request))

有没有正确的重定向,仍然通过RequestContext?

Is there anyway to have a proper redirect, and still pass RequestContext along?

推荐答案

RequestContext 只用于在渲染模板时将值传递给模板引擎。目的地视图不应该依赖于起始视图的 RequestContext ,它应该能够生成它自己的RequestContext。

RequestContext is only used to pass values to the template engine when a template is rendered. The destination view shouldn't depend on the RequestContext from the originating view, it should be able to generate it's own RequestContext.

在某些情况下,您需要在这样的视图之间传递值。在这些情况下,您可以使用querystring值来执行此操作。例如...

There are situations however where you need to pass values between views like this. In these situations you can use querystring values to do so. For example...

def originating_view(request, *args, **kwargs):
    return HttpResponseRedirect('/accounts/login/?username=%s&next=%s' % (username, request.path)

def destination_view(request, *args, **kwargs):
    # Get the username from the querystring
    username = request.GET.get('username', None)
    next = request.GET.get('next', '/')

    if username:
        # ...

(请注意,假设您要保留用户名的原因是将其预先填充到登录表单中。如果您正在执行实际登录,则需要使用POST,以使用户名和密码不会记录在URL中的纯文本)。

这篇关于Django:HttpResponseRedirect不通过RequestContext()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆