django中缺少csrf令牌
我对django csrf有问题。这是我的视图代码django中缺少csrf令牌,django,csrf,Django,Csrf,我对django csrf有问题。这是我的视图代码 if request.user.is_authenticated(): res = {"is_authenticated": "true"} else: res = {} return render_to_response('app/index.html', res, context_instance=RequestContext(request)) 检查CsrfViewMiddleware是
if request.user.is_authenticated():
res = {"is_authenticated": "true"}
else:
res = {}
return render_to_response('app/index.html', res, context_instance=RequestContext(request))
检查
CsrfViewMiddleware
是否已添加到settings.py中的MIDDLEWARE\u类
元组中,然后您只需在模板内执行{%csrf\u token%}
即可获取令牌
设置.py
MIDDLEWARE_CLASSES = (
...
...
'django.middleware.csrf.CsrfViewMiddleware',
...
...
)
app/index.html
<form action="" method="post">{% csrf_token %}
{%csrf\u令牌%}
有关详细信息,请参阅。在您的视图中。py请在函数上方使用@csrf\u employ decorator,因为需要像这样首先导入此decorator
from django.views.decorators.csrf import csrf_exempt
<form method="" action="">
{% csrf_token %}
.......
</form>
然后在你的视图函数中使用它
@csrf_exempt
def sample_func(request):
if request.user.is_authenticated():
res = {"is_authenticated": "true"}
else:
res = {}
return render_to_response('app/index.html', res, context_instance=RequestContext(request))
然后在index.html文件中调用这个decorator表单标记,如下所示
from django.views.decorators.csrf import csrf_exempt
<form method="" action="">
{% csrf_token %}
.......
</form>
{%csrf_令牌%}
.......
您能否更准确地说明错误出在哪里?通常情况下,当您的表单中缺少csrf\u token
标记时,会出现此问题。可能是重复的No。您不应该给出这样的建议。CSRF保护是有原因的;随机禁用它几乎总是错误的。