[Fixed]-Forms in django, overriding validation on file upload to make sure just one value is there

1👍

You should set your fields to required=False, which will avoid a validation error if any field is empty:

docfile3 = forms.FileField(
    label='Select a file',
    help_text='max. 7 Gigabytes',
    required=False
)

Then in your form clean method check to see if at least one file is there:

from django.core.exceptions import ValidationError

def clean(self):
    data = super(DocumentForm, self).clean()

    # if there are already form errors, don't proceed with additional
    # validation because it may depend on fields which didn't validate.
    if self.errors:
        return data

    if not (data['docfile1'] or data['docfile2'] or data['docfile3']):
        return ValidationError('You must upload at least one file.')

    return data

I have not actually run this code so there may be some little issue but you get the idea…

In your view form_valid() method, there are problems with your saving code. Do something more like this:

for fieldname in ('docfile', 'docfile2', 'docfile3'):
    file = form.cleaned_data.get(fieldname, None)
    if file:
        Document(docfile = file).save()

Leave a comment