6
回答
Django 表单提交出现 CSRF verification failed. Request aborted
利用AWS快速构建适用于生产的无服务器应用程序,免费试用12个月>>>   

我是个 Django 初学者,在做一个表单的时候,提交出现下面错误,是怎么回事呢?

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:

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

举报
铁血战士
发帖于6年前 6回/17K+阅
共有6个答案 最后回答: 1年前

解决方法错误提示里已经给出了。在表单里加上{% csrf_token %}就行了。

第二种放发是在Settings里的MIDDLEWARE_CLASSES增加配置:

'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',

这种方式违反了django的初衷,正确的解决方案有两个:
1.引入RequestContext:
from django.shortcuts import render_to_response, get_object_or_404,
from django.template import RequestContext

def edit(request, id):
publisher = get_object_or_404(Publisher, id=id)
if request.method == 'POST':
appForm = PublisherForm(request.POST, instance = publisher)
if appForm.is_valid():
publisher = appForm.save();
publisher.save()
return HttpResponseRedirect(reverse("index"))
return render_to_response('books/edit.html', {'form': PublisherForm(instance = publisher)}, context_instance=RequestContext(request))
2.使用render方式渲染页面:
from django.shortcuts import render_to_response, get_object_or_404, render
def edit(request, id):
同上
#return render_to_response('books/edit.html', {'form': PublisherForm(instance = publisher)}, context_instance=RequestContext(request))
return render(request, 'books/edit.html', {'form': PublisherForm(instance = publisher)})
  • 由于我们创建一个POST表单(它具有修改数据的作用),所以我们需要小心跨站点请求伪造。 谢天谢地,你不必太过担心,因为Django已经拥有一个用来防御它的非常容易使用的系统。 简而言之,所有针对内部URL的POST表单都应该使用{% csrf_token %}模板标签。
  • 参考资料:http://python.usyiyi.cn/django/intro/tutorial04.html

  1. django 禁用CSRF 的方法:
  2. 修改C:\Python27\Lib\site-packages\django\middleware\csrf.py
#找到如下代码:
if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): 
#修改为:
if request.method not in ('GET','POST', 'HEAD', 'OPTIONS', 'TRACE'):




顶部