[Answer]-Django: Applying clean method on per-file, rather than per-form basis?

1👍

My 2 cents: you should bypass the form validation framework for this. Attaching errors to a form field name is heavily built into the framework.

Instead, why not store the custom errors in an attribute or method on the form object?

{% if form.images.errors %}
    {% for image, error in form.more_detailed_images_errors %}
       Your image {{ image }} has an error: {{ error }}
    {% endfor %%
{% endif %}

class MyForm(...):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.more_detailed_image_errors = []

    def clean_images(self):
        #...
        for image in images:
            # validate image
            if image_is_invalid:
                error_msg = 'This image is invalid for reason X'
                # presumably this is your dynamic error message
                self.more_detailed_image_errors.append((image, error_msg))
        if self.more_detailed_image_errors:
            raise ValidationError("You've uploaded invalid images")

Leave a comment