## 11.6 通过 Form.add_error() 添加错误到表单


Michael Barr与我们分享,自从Django 1.7开始我们可以通过Form.add error()方法简化Form.clean()

  1. EXAMPLE 11.8
  2. from django import forms
  3. class IceCreamReviewForm(forms.Form):
  4. # Rest of tester form goes here
  5. # 表单测试的其余部分
  6. ...
  7. def clean(self):
  8. cleaned_data = super(TasterForm, self).clean()
  9. flavor = cleaned_data.get("flavor")
  10. age = cleaned_data.get("age")
  11. if flavor == 'coffee' and age < 3:
  12. # Record errors that will be displayed later.
  13. # 稍后将显示错误记录。
  14. msg = u"Coffee Ice Cream is not for Babies."
  15. self.add_error('flavor', msg)
  16. self.add_error('age', msg)
  17. # Always return the full collection of cleaned data.
  18. # 总是返回完整的清理的数据的收集。
  19. return cleaned_data

11.6.1 其他的实用表单方法

这里有些值得探索的表单验证方法:

        http://www.2scoops.co/1.8-form.errors.as_data/

        http://www.2scoops.co/1.8-form.errors.as_json/

        http://www.2scoops.co/1.8-form.has_error/

        http://www.2scoops.co/1.8-form.non_field_errors/