CSRF verification failed. Request aborted.

—————Django1.6————

Forbidden (403)

CSRF verification failed. Request aborted.

Help

Reason given for failure:

    CSRF token missing or incorrect.
    

In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure:

  • Your browser is accepting cookies.
  • The view function uses RequestContext for the template, instead of Context.
  • In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
  • If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data.

You're seeing the help section of this page because you have DEBUG = True in your Django settings file. Change that to False, and only the initial error message will be displayed.

You can customize this page using the CSRF_FAILURE_VIEW setting.

当我们在页面中有post方式的form的时候,如果不注意就会出现这种情况,这是因为Django对于CSRF的处理...

至于什么是CSRF,可以参看大神の见解

如果我们将settings.py中MIDDLE_CLASSES的'django.middleware.csrf.CsrfViewMiddleware'删掉的话,就不会出现这问题...当然这是不科学的...这样就没有对CSRF进行处理了...

其实解决方法在给出的错误信息中已经说明白了:

1、浏览器要支持cookie

2、确保在视图方法中“django.core.context_processors.csrf”被使用,确保它被使用的方法可以是:

  a、视图方法中使用RequestContext来代替Context,这样就能确保它被调用,此时要认识到,render_to_response这个默认是使用的Context...

render_to_response('xx.html',your_dict,context_instance=RequestContext(request))

 这样一改的话就可以了,也可以使用render。。。

  b、-.- 看的懂英文,中文说不出个所以然来...直接上文档中的代码...

from django.core.context_processors import csrf
from django.shortcuts import render_to_response

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

3、在模块中,要使用{% csrf_token %}

<form action="{% url 'polls:vote' poll.id %}" method="post" >
{% csrf_token %}
        <input name="name" />
</form>

4、我们也可以不在settings.py中配置CsrfViewMiddleware,而是在每个需要使用到的视图方法中使用csrf_protect装饰器

做完这个你肯定以为可以搞定了吧... =、= 我也是这么认为的...可以就是因为一个问题导致没成功...折磨了很久...

- - 关键在于第二点,使用RequestContext这个问题上,这东西是要在进入有{% csrf_token %}的这个template前的view中使用的,假如说我们在index.html中有post表单,而我们进入index.html前的view function是

def index(request) 。。。那么没错了,就是在这个index方法中使用RequestContext...

其实主要还是因为不知道CSRF是啥东西...看完那篇之后也就比较明白为什么会这样了...

原文地址:https://www.cnblogs.com/lazyzhong/p/3507988.html