Skip to main content
 首页 » 编程设计

python之Django 基于多个字段(文件字段)验证表单

2024年09月03日33webabcd

django 中有没有一种方法可以基于多个字段验证表单。我见过一些示例,其中人们建议重写表单的 clean 方法并在无法满足您的自定义验证时引发 ValidationError。我的问题是我不确定您是否可以检查文件是否是从 clean 方法中上传的。我只能使用请求对象访问它们,而您无法在表单的 clean 方法中访问请求对象。

请您参考如下方法:

您所描述的方法(从 Form.clean 中引发 ValidationError)是执行 multi-field validation 的官方方法.

您可以在 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 {} 
        ...