Django1.4之CSRF错误以及解决方法 20

来源:互联网 发布:sklearn iris数据集 编辑:程序博客网 时间:2024/06/08 17:19
在创建一个站点联系表单的时候,表单如下:

点击(此处)折叠或打开

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  2.         "http://www.w3.org/TR/html4/loose.dtd">
  3. <html>
  4. <head>
  5.     <title>联系我们</title>
  6. </head>
  7. <body>
  8.     <h1>联系我们</h1>
  9.     {% if errors %}
  10.         <ul>
  11.             {% for error in errors %}
  12.                 <li>{{ error }}</li>
  13.             {% endfor %}
  14.         </ul>
  15.     {% endif %}
  16.     <form action="/contact/" method="post">{% csrf_token %}
  17.         <p>主题: <input type="text" name="subject"></p>
  18.         <p>邮箱地址 (可选): <input type="text" name="email"></p>
  19.         <p>信息: <textarea name="message" rows="10" cols="50"></textarea></p>
  20.         <input type="submit" value="提交">
  21.     </form>

  22. </body>
  23. </html>
运行django,点击提交之后,出现以下错误:

点击(此处)折叠或打开

  1. Forbidden (403)
  2. CSRF verification failed. Request aborted.
  3. Help
  4. Reason given for failure:
  5. CSRF token missing or incorrect.
  6. 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:
  7. 1)Your browser is accepting cookies.
  8. 2)The view function uses RequestContext for the template, instead of Context.
  9. 3)In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL.
  10. 4)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.
出现这种情况的原因,在django开启了debug功能后已经被列出了,其中1)、3)以及4)操作都已经做了,但是还是出现了错误,查看django1.4官方文档,在视图views.py中还需要进行相应的调整,也就是渲染模板时,不能简单的使用Context,而应该使用RequestContext来代替它,调整之后视图代码如下:

点击(此处)折叠或打开

  1. from django.shortcuts import render_to_response
  2. from django.http import HttpResponseRedirect
  3. from django.core.mail import send_mail
  4. from django.template import RequestContext

  5. def contact(request):
  6.     errors = []

  7.     if request.method == 'POST':
  8.         if not request.POST.get('subject', ''):
  9.             errors.append('Enter a subject')
  10.         if not request.POST.get('message', ''):
  11.             errors.append('Enter a message')
  12.         if request.POST.get('email') and '@' not in request.POST['email']:
  13.             errors.append('Enter a valid e-mail address')
  14.         if not errors:
  15.             send_mail(request.POST['subject'], request.POST['message'],
  16.                 request.POST.get('email', 'zqlongqiang@gmail.com'),['long_xitianxia@126.com',])
  17.             return HttpResponseRedirect('thanks')

  18.     return render_to_response('contact_form.html',
  19.             RequestContext(request,{'errors': errors}))
也就是修改21-22的代码,把原来的两行代码(如下)
  1. return render_to_response('contact_form.html',
  2.             {'errors': errors})#默认为Context
修改成:
  1.  return render_to_response('contact_form.html',
  2.             RequestContext(request,{'errors': errors}))
这样问题就得以解决了!


注:  仅能解决不适用forms。py 自校验程序,加入forms.py 以后报错。
http://djangobook.py3k.cn/2.0/chapter07/ 处例子

  --- 新的一天,重启应用测试发现好了,真奇特啊!