解決Django 提交表單時403錯誤:CSRF verification failed. Request aborted .


Django提交表單報錯以下:
html

Forbidden (403)

CSRF verification failed. Request aborted.python

Help

Reason given for failure:django

    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:cookie

  • Your browser is accepting cookies.ide

  • The view function passes a request to the template's render    method.ui

  • In the template, there is a {% csrf_token    %} template tag inside each POST form that    targets an internal URL.this

  • 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.spa

  • The form has a valid CSRF token. After logging in in another browser    tab or hitting the back button after a login, you may need to reload the    page with the form, because the token is rotated after a login..net

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.code

You can customize this page using the CSRF_FAILURE_VIEW setting.




解決辦法(按照辦法一解決):


1、

settings.py,在 MIDDLEWARE_CLASSES 中註釋掉 'django.middleware.csrf.CsrfViewMiddleware',


2、

1.檢查settings.py,發如今 MIDDLEWARE_CLASSES 中添加 'django.middleware.csrf.CsrfViewMiddleware', 選項

發如今django1.5.9裏已默認開啓。

2.在模板的form體裏面,加入 {% csrf_token %}   例如:

< form action = "" method = "POST" >
{% csrf_token %}
......
.....
</ form >


3.在view裏面,強制使用RequestContext 代替Context。示例以下:

from django.template import RequestContext

視圖返回要這樣:

return render_to_response(‘index.html’,
                   { 'param1′: ' aaa ',' param2′: 'bbb' ,},
                   context_instance = RequestContext(request)
                  )

轉載自:

http://www.91pen.net/slove-the-problem-when-the-django-form-submitted-occur-403-error-csrf-verification-failed-request-aborted.html

相關文章
相關標籤/搜索