custom file validation

23 views
Skip to first unread message

deecodameeko

unread,
Sep 3, 2010, 10:52:48 AM9/3/10
to Django users
Hi,

I have a file in a form. The file is optional but if the file is not
None, then some other form fields are required as well. For example
the following code checks one of the fields that's required when the
file fields isn't empty:

file = forms.FileField(required=False)

def clean_canvas_height(self):

canvas_height = self.cleaned_data['canvas_height']
file = self.cleaned_data['file']
if file is not None and canvas_height is None:
raise forms.ValidationError('You must specify a canvas
height')
return canvas_height

this produces a KeyError which I'm gathering I can't access the file
info this way. My question is how can I go about writting a custom
validation against a file field.

Cheers!

D

Shawn Milochik

unread,
Sep 3, 2010, 11:18:27 AM9/3/10
to django...@googlegroups.com
Any validation which has to do with multiple fields should be done in
the clean() override, not within the individual field validator.

You can't rely on cleaned_data existing before that point.

http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other

Shawn

ringemup

unread,
Sep 3, 2010, 11:23:55 AM9/3/10
to Django users

Two things going on here:

1) Validation that involves checking multiple fields should be done in
the form's clean() method rather than its clean_FIELDNAME method. Not
all fields are guaranteed to have been added to cleaned_data until you
reach the clean() method.

2) Try using self.cleaned_data.get('canvas_height') and
self.cleaned_data.get('file') instead of directly referencing the
dictionary indices. get() will return None if the key is not found
(or if the value is None), whereas accessing the index will throw a
KeyError if the key is not found -- which you then need to catch if
you don't want to interrupt script execution.

deecodameeko

unread,
Sep 3, 2010, 11:50:25 AM9/3/10
to Django users
Thanks guys,

I switched to using the clean method to check multiple fields however
the file is always None even if I have browsed and found a file I want
to upload.

def clean(self):

cleaned_data = self.cleaned_data
store_id = cleaned_data.get('store_id')
category_id = cleaned_data.get('category_id')
gender = cleaned_data.get('gender')
file = cleaned_data.get('file')

if (store_id != '0' or category_id != '0' or gender !=
'0') and file is None:
msg = 'You must specify a file to upload'
self._errors['file'] = self.error_class([msg])

return cleaned_data

deecodameeko

unread,
Sep 3, 2010, 4:50:23 PM9/3/10
to Django users
My bad...twas failiing cuz I didn't spell enctype properly...all good.
Reply all
Reply to author
Forward
0 new messages