Django --CSRF令牌丢失或不正确 [英] Django --CSRF token missing or incorrect

查看:135
本文介绍了Django --CSRF令牌丢失或不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我得到禁止(403)CSRF验证失败。请求中止。给予失败的原因:CSRF令牌丢失或不正确。

我的中间件类中有'django.middleware.csrf.CsrfViewMiddleware'。
这是我的模板

So I am getting Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: CSRF token missing or incorrect.
I have the 'django.middleware.csrf.CsrfViewMiddleware', in my middleware_classes. Here is my template

<form name="input" action="/login/" method="Post"> {% csrf_token %}
<input type="submit" value="Submit"></form>

这是我的观点

from django.shortcuts import render_to_response
from django.core.context_processors import csrf
from django.template import RequestContext
def login(request):
     csrfContext = RequestContext(request)
     return render_to_response('foo.html', csrfContext)

我是Django和大多数Web开发的新手,但我似乎在这里找不到问题。任何帮助将不胜感激!

Well I am new to Django and most web development, but I cannot seem to find the problem here. Any help would be much appreciated!

此外,我已经尝试了django文档中的方法

Also i have tried the method in the django documentation

c = {}
c.update(csrf(request))
# ... view code here
return render_to_response("a_template.html", c)


推荐答案

尝试在登录功能之前添加@csrf_protect装饰器。

Try adding the @csrf_protect decorator just before your login function.

from django.views.decorators.csrf import csrf_protect

@csrf_protect
def login(request):
     csrfContext = RequestContext(request)
     return render_to_response('foo.html', csrfContext)

如果表单不在foo.html中,则需要将@csrf_protect方法添加到生成它的视图函数中。

If the form is not in foo.html then you need to add the @csrf_protect method to the view function that is generating it.

这篇关于Django --CSRF令牌丢失或不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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