django1.62提交POST报错CSRF verification failed

本文介绍了如何解决Django框架中常见的CSRF验证失败问题,包括配置中间件、使用正确的模板标签及视图装饰器。
复制代码
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.
复制代码




解决方法1:

1 In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.在表单里加上{% csrf_token %}。

2 在setting.py 中设置文件如下:

复制代码
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',                       <-------------------新加入 DJANGO <= 1.3
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.csrf.CsrfResponseMiddleware'                    <-------------------新加入 DJANGO 1.4
    # Uncomment the next line for simple clickjacking protection:
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
复制代码

 但是如果在1.4版本中加入的话又会出现以下问题:

复制代码
Traceback (most recent call last):
  File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/usr/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 67, in __call__
    return self.application(environ, start_response)
  File "/usr/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 219, in __call__
    self.load_middleware()
  File "/usr/lib/python2.7/site-packages/django/core/handlers/base.py", line 51, in load_middleware
    raise exceptions.ImproperlyConfigured('Middleware module "%s" does not define a "%s" class' % (mw_module, mw_classname))
ImproperlyConfigured: Middleware module "django.middleware.csrf" does not define a "CsrfResponseMiddleware" class
Validating models...
复制代码

找不到CsrfResponseMiddleware 这个类:

官方文档是这么说的:

Use of the CsrfResponseMiddleware is not recommended because of the performance hit it imposes, and because of a potential security problem (see below). It can be used as an interim measure until applications have been updated to use the csrf_token tag. It is deprecated and will be removed in Django 1.4.

所以上边第二个新加入的东西要删掉,在template文件中的form中加入tag {% csrf_token %} 如下:

复制代码
<form action="/books/contact/" method="post">
                {% csrf_token %}                             <--------------------------------------新加入的
                <p>Subject: <input type="text" name="subject"></p>
                <p>Your e-mail: (optional): <input type="text" name="email"></p>
                <p>Message: <textarea name="message" rows="10" cols="50"></textarea></p>
                <input type="submit" value="Submit">
        </form>
复制代码

加上了之后我运行还是不行:还需要最后一步:在view文件中加入装饰器@csrf_exempt如下:

 
 

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def contact(request):

问题终于解决掉!!!


解决方法2:

1,在view里面,强制使用RequestContext 代替Context。示例如下:

from django.template import RequestContext   

视图返回要这样:

        return render_to_response('index.html', context_instance=RequestContext(request) 
        )

2,在模板的form体里面,加入 {% csrf_token %},示例如下:

    <form action="login.html" method="post" >
       {% csrf_token %}   

      ……

    </form>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值