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

发布于 2024-10-02 04:24:08 字数 168 浏览 3 评论 0原文

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

Is there a way in django to validate a form based on multiple fields. I have seen some examples where people recommend overriding a form's clean method and raising a ValidationError if it fails to meet your custom validation. The problem for me is that I'm not sure you can check whether or not a file was uploaded from within the clean method. I have only been able to access them using the request objects and you do not have access to the request object within the form's clean method.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若相惜即相离 2024-10-09 04:24:08

您所描述的方法(从 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 {}
        ...

The method you've described (raising ValidationError from within Form.clean) is the official way to do multi-field validation.

You can access uploaded files from self.files within the clean method. 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 {}
        ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文