0

单击虚拟表单的提交按钮时出现以下错误

禁止 (403)

CSRF 验证失败。请求中止

我的views.py(已经完成了上面所需的导入)如下所示:

def search(request):
       errors=[]
       if request.method=="POST":
             if not request.POST['name']:
                       errors.append('Name field is empty')
             if not request.POST['subject']:
                       errors.append('Subject field is empty')
             if not request.POST['age']:
                       errors.append('Age field is empty')
             if not errors:
                       thank()
       return render_to_response('search.html',{'errors':errors},context_instance=RequestContext(request))

def thank(search):
      return HttpResponse('<html><p>Post done successfully</p></html>')

我的 search.html 是:

    <form method="post" action='/search/'>
     <p>Name: <input type="text" name="name"/></p>
     <p>Subject  <input type="text" name="subject"/></p>
     <p>Age: <input type="text" name="age"/></p>
     <input type="submit" value="Hit Me!!"/>
    </form>
  </body>
 </html>

有人请让我知道,我该如何克服这个错误?

4

2 回答 2

0

我要说的是,我{% csrf_token %}在您的<form></form>标签之间看不到a。这将导致 CSRF 验证失败。上面的海报打败了我。

于 2012-05-12T14:12:34.817 回答
0

出色地,

1. 将 'django.core.context_processors.csrf' 添加到 settings.py 中的 TEMPLATE_CONTEXT_PROCESSORS 设置。2.像这样修改你的表格,

<form method="post" action='/search/'>
  {% csrf_token %}
  <p>Name: <input type="text" name="name"/></p>
  <p>Subject  <input type="text" name="subject"/></p>
  <p>Age: <input type="text" name="age"/></p>
  <input type="submit" value="Hit Me!!"/>
</form>
于 2012-05-12T11:52:58.003 回答