2
django有没有方法基于多个字段验证表单。我见过一些例子,其中人们建议覆盖表单的干净方法,如果它无法满足您的自定义验证,则引发ValidationError。对我而言,问题在于我不确定是否可以检查是否从clean方法中上传文件。我只能使用请求对象访问它们,并且您无法访问表单干净方法中的请求对象。Django基于多个字段验证表单(文件字段)
django有没有方法基于多个字段验证表单。我见过一些例子,其中人们建议覆盖表单的干净方法,如果它无法满足您的自定义验证,则引发ValidationError。对我而言,问题在于我不确定是否可以检查是否从clean方法中上传文件。我只能使用请求对象访问它们,并且您无法访问表单干净方法中的请求对象。Django基于多个字段验证表单(文件字段)
您描述的方法(从Form.clean
中提出ValidationError
)是执行multi-field validation的官方方式。
您可以在clean
方法内访问self.files
上传的文件。 From 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 {}
...