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
On Sep 3, 11:23 am, ringemup <ringe...@gmail.com> wrote:
> 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.
>
> On Sep 3, 10:52 am, deecodameeko <deecodame...@gmail.com> wrote:
>
> > 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
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
No comments:
Post a Comment