放置 ModelForm 验证的正确位置是什么?
我正在使用 Django 的 ModelForms,并且希望对模型和表单进行验证。我正在使用以下方式渲染表单:
{{ form.as_table }}
在每个字段的基础上(如表单的 clean_fieldname
)和作为一个整体(如表单的 clean
)进行验证的正确位置是什么? ?
我希望最大限度地减少编写的代码量,并且不要两次编写相同的验证器(在模型和表单中)。另外,我希望在正确的表单字段上显示每个字段的验证错误,而不是将所有错误都放在表单顶部(因此并非模型中的所有检查都是干净的)。
I'm using Django's ModelForms
and would like to have validation on both models and forms. I'm rendering form using:
{{ form.as_table }}
What is the proper place to put validation on per-field basis (like forms' clean_fieldname
) and as a whole (like forms' clean
)?
I'd like to minimize amount of code written and not write the same validators twice (in both models and forms). Also, I'd like per-field validation errors to be shown over proper form field, not have all errors placed on top of the form (so not all checks in models' clean).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能想要使用 Django 1.2 中引入的自定义 验证器。
不要忘记,除非您使用
ModelForm
,否则您必须通过调用 full_clean() 模型实例上的方法。You might want to use the custom validators introduced in Django 1.2.
Don't forget that unless you are using a
ModelForm
you have to explicitly performs the model validation with a call to the full_clean() method on your model instance.