Django根据多个字段(文件字段)验证表单
在Django中,有没有办法根据多个字段来验证一个表单?我看到一些例子,大家建议重写表单的clean方法,如果不符合自定义的验证规则,就抛出一个ValidationError(验证错误)。但我遇到的问题是,我不确定在clean方法里能否检查是否上传了文件。我只能通过请求对象来访问这些文件,而在表单的clean方法中是无法访问请求对象的。
1 个回答
3
你提到的方法(在 Form.clean
里面抛出 ValidationError
)是进行多字段验证的官方做法。
你可以在 clean
方法中通过 self.files
来访问上传的文件。这个信息来自 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 {}
...