使用/ csrf上下文帮助传递变量

时间:2011-07-20 18:11:37

标签: python django csrf

我有一个登录页面,在我的视图中,我传递了csrf_token标记的csrfContext变量。但是,当我尝试将不仅仅是该变量传递给上下文时,就会出现问题。例如,如果我使用locals()

return render_to_response('base_index.html', locals())

我收到了csrf错误。出于某种原因,只有在我明确传递csrfContext并且只传递csrfContext时它才有效。但是,我还需要传递其他变量。如何将csrfContext和这些变量一起传递?对不起,如果这是一个令人费解的问题。我的观看代码是:

def index(request):
    current = Module.objects.all()
    error = ""
    try:
        error = request.GET["alert"]
        if error == "failure":
            error = "Woops! Something went wrong. Please try again."
        elif error == "invalid":
            error = "Invalid username/password."
        else:
            error = "Unknown Error. Please try again."
    except:
        pass
    csrfContext = RequestContext(request, error, current)
    return render_to_response('base_index.html', csrfContext)

正如您所看到的,我一直在尝试向RequestContext添加变量,但我不知道如何在模板中访问它们。

2 个答案:

答案 0 :(得分:0)

我不建议以这种方式使用locals()。在更复杂的视图中,您最终可能会将更多内容传递给所需的模板渲染。

更好的方法是创建RequestContext,并传入要添加的值,或者在以下后添加:https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.Context

答案 1 :(得分:0)

我使用return render_to_response('base_index.html', locals(), csrfContext)并且有效