newforms: form.clean conundrum

0 views
Skip to first unread message

Gary Doades

unread,
Jan 26, 2007, 11:16:52 AM1/26/07
to Django developers
I've just got to write my first form.clean method. I need to to do some
complex validation of different combinations of fields depending on the
setting of one other field.

This works great until one or more of the individual field validations
fail.

In my form.clean method I'm using the self.clean_data dict as already
filled in by the individual field.clean methods. This seems like the
way to go so as not to repeat the field validations. However, if a fild
validation fails an entry for that field is not made in the clean_data
dict, but an entry is added to the local var errors dict.

Without testing for the presence of each value within clean_data, I see
no way of telling whether any individual field has failed it own
validation or not. As far as I am concerned, if any individual field
fails validation then there is no point in doing any more validation
for combinations of fields. There may be people who do want to do this
though. I see two solutions:

1) don't call form.clean() if any individual field validation fails

2) pass in the local errors[] dict populated from the field.clean()
calls into form.clean() so we can see if there were indeed any failed
fields and decide if we want to carry on validation in form.clean() or
not.

Regards,
Gary.

Ceph

unread,
Feb 2, 2007, 11:06:04 AM2/2/07
to Django developers
I actually just ran into this problem. I was assuming that if my
form's clean() hook were called, that clean_data would have at the
very least empty entries for the already-validated fields. In my case,
I don't need to do complex validation (database hits) unless the
previous fields are valid, and testing for self.is_valid() or using
bool(self.errors) in turn re-calls clean(), e.g., infinite recursion.

I can see having access to the ErrorDict as being useful. Particularly
since you can do your validation based on individual field errors.

Reply all
Reply to author
Forward
0 new messages