django中有没有办法根据多个字段验证表单。我看过一些例子,人们建议覆盖表单的clean方法,如果无法满足自定义验证,则会引发ValidationError。对我来说问题是我不确定你是否可以检查文件是否是从clean方法中上传的。我只能使用请求对象访问它们,并且您无法访问表单的clean方法中的请求对象。
答案 0 :(得分:3)
您所描述的方法(在ValidationError
内提出Form.clean
)是执行multi-field validation的官方方式。
您可以在self.files
方法中访问clean
上传的文件。来自django/forms/forms.py
:
class BaseForm(StrAndUnicode):
# This is the main implementation of all the Form logic. Note that this
# class is different than Form. See the comments by the Form class for more
# information. Any improvements to the form API should be made to *this*
# class, not to the Form class.
def __init__(self, data=None, files=None, ...):
self.is_bound = data is not None or files is not None
self.data = data or {}
self.files = files or {}
...