最新消息:

Django表单提交出现 CSRF verification failed. Request aborted

Django admin 1903浏览 0评论

20131220105050

如上图所示,在用表单提交post数据时出现了403,而用get方式提交表单数据时就没有存在上述问题。经过查阅资料,出现上述403错误的原因是Django对csrf的防护措施。要使表单正确的提交POST数据,需采取一下措施:

1、检查settings.py配置文件中的MIDDLEWARE_CLASSES参数中是否存在django.middleware.csrf.CsrfViewMiddleware,如果不存在就添加。

20131220105504

2、修改视图函数,使用RequestContext而不是Context

from django.template import Context,RequestContext

def form(request):
    if 'q' in request.POST:
        return HttpResponse('input is %s' %request.POST['q'])
    else:
        return render_to_response('form.html',{},context_instance=RequestContext(request))

3、在form表单所在的模板中添加{% csrf_token %}标签

<head>
<title>表单提交</title>
</head>
<body>
<form action="" method="post">
    {% csrf_token %}
    <input type="text" name="q" >
    <input type="submit" value="提交" />
</form>
</body>

ps:采取上面三个措施之后,进行POST数据提交就不会出现403错误了。此时查看生成的form表单,可以看到Django为表单添加了一个隐藏字段来防止CSRF攻击。

20131220110253

 

转载请注明:jinglingshu的博客 » Django表单提交出现 CSRF verification failed. Request aborted


Warning: Use of undefined constant PRC - assumed 'PRC' (this will throw an Error in a future version of PHP) in /usr/share/nginx/html/wp-content/themes/d8/comments.php on line 17
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (1)

  1. I have noticed you don't monetize your blog, don't waste your traffic, you can earn additional cash every month because you've got high quality content. If you want to know how to make extra bucks, search for: Mertiso's tips best adsense alternative
    LastDiane3年前 (2018-01-12)回复