CSRF令牌丢失或错误,即使我有{%csrf_token%} [英] CSRF token missing or incorrect even though I have {% csrf_token %}

查看:910
本文介绍了CSRF令牌丢失或错误,即使我有{%csrf_token%}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的views.py文件中引用了这个方法:

I have been getting this error referring to this method in my views.py file:

def AddNewUser(request):
    a=AMI()
    if(request.method == "POST"):
        print(request.POST)
       # print(request['newUser'])
       # print(request['password'])
    return render_to_response("ac/AddNewUser.html", {})

但是我的其他功能很好。只是我的HTML文件中的这个按钮不起作用。

But my other functions work just fine. It's just this button in my HTML file that doesn't work.

< form name =AddNewUseraction =/ ac / AddNewUsermethod =post> {%csrf_token%}< input type =submitname =addNewUserid =addNewUservalue =创建用户>< / form>

你可以看到我有{%csrf_token%}但仍然没有工作。我也知道有些人在他们的settings.py中没有MIDDLEWARE_CLASSES的时候遇到这个问题,但是我已经正确插入了。可能导致这个问题?错误中唯一的其他行说:视图函数使用RequestContext作为模板,而不是Context。但我不知道这可能意味着什么。

As you can see I've got the {% csrf_token %} but it's still not working. I also know some people are having this problem if they don't have MIDDLEWARE_CLASSES in their settings.py but I have that inserted correctly. What could be causing this problem? The only other line in the error says: "The view function uses RequestContext for the template, instead of Context." But I don't know what that could mean.

推荐答案

您必须使用 RequestContext 对象来获取上下文,然后将结果传递给您的 render_to_response()函数。 RequestContext 添加一个必需的CSRF令牌。

You have to use a RequestContext object to get the context, then pass the results in to your render_to_response() function. RequestContext adds in a required CSRF token.

from django.template import RequestContext
from django.shortcuts import render_to_response

csrfContext = RequestContext(request)
return render_to_response(some_template, csrfContext)

作为附注,您还可以使用 RequestContext 添加旨在为模板使用的上下文/字典。例如,我经常使用:

As a side note, you can also use RequestContext to add contexts/dictionaries intended for the template. For instance, I frequently use:

initialData = {'form': theForm, 'user_status': 'online'}
csrfContext = RequestContext(request, initialData)
return render_to_response(show_template, csrfContext)

作为对RequestContext 所做的(简要)说明:大多数中间件创建一个称为上下文处理器的东西,这只是一个提供变量的上下文(字典)的函数。 RequestContext 查找所有可用的上下文处理器,获取上下文,并将它们全部附加到单个(巨型)上下文中。

As a (brief) explanation of what RequestContext does: most middleware creates something called a context processor, which is simply a function that supplies a context (dictionary) of variables. RequestContext looks for all the available context processors, gets their contexts, and appends them all to a single (giant) context.

这篇关于CSRF令牌丢失或错误,即使我有{%csrf_token%}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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