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 ofContext
. - 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 usecsrf_protect
on any views that use thecsrf_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是啥东西...看完那篇之后也就比较明白为什么会这样了...
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!