Reputation: 1746
I'm trying to do something similar to this:
Django: How to write a clean method for a field that allows mutiple file uploads?
The user can upload one or more files using
<input type="file" name="images" multiple="multiple">
If I use the code provided in the accepted answer ...
def clean_images(self):
files = self.files.getlist('images')
for file in files:
if file:
if file._size > 15*1024*1024:
raise forms.ValidationError("Image file is too large ( > 15mb ).")
else:
raise forms.ValidationError("Could not read the uploaded file.")
return files
... and then do form.is_valid()
, it will return False
if any of the uploaded files are problematic.
What I'd like to do is be able to determine which files are clean and which aren't, process the valid ones, and tell the user why the invalid ones are invalid.
So, is it possible to apply the clean method on a per-file basis -- i.e., to pull the getlist
loop out of the clean method and instead run the clean method from within the loop?
Upvotes: 0
Views: 190
Reputation: 118488
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")
Upvotes: 1