【问题标题】:Django forms Forbidden (403) errorDjango 表单禁止 (403) 错误
【发布时间】:2012-05-20 18:11:48
【问题描述】:

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

禁止 (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>

有人请告诉我,我该如何克服这个错误?

【问题讨论】:

    标签: django-forms


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      嗯,

      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>
      

      【讨论】:

        猜你喜欢
        • 2018-02-28
        • 1970-01-01
        • 2013-06-27
        • 2021-09-25
        • 2021-10-03
        • 1970-01-01
        • 2013-05-25
        • 1970-01-01
        相关资源
        最近更新 更多