Alex Amato
Alex Amato

Reputation: 1591

Django validate form based on multiple fields (file fields)

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.

Upvotes: 2

Views: 3195

Answers (1)

eternicode
eternicode

Reputation: 6935

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 {}
        ...

Upvotes: 3

Related Questions