Custom Field Validation and Required Fields

253 views
Skip to first unread message

Ian Strachan

unread,
Nov 4, 2012, 5:40:46 PM11/4/12
to django-res...@googlegroups.com
I'm adding in some custom validation at the moment and I'm finding that if the field I'm validating has already failed one of the built in DRF validations then the value isn't included in the attrs dictionary passed in.  For example, if "username" is required then my validate_user function wont be supplied a username value in attrs to validate.  This is resulting in me writing lots of identical exception handling code to prevent possible errors before I can do my actual validation:

def validate_username(self, attrs, source):
        try:
            username = attrs[source]
        except KeyError:
            return attrs
        # actual validation goes here

Maybe this kind of makes sense because a username isn't supplied but I'm also having to do similar with an email field if the email address supplied doesn't match the regex it is tested against.  Would it make sense to either pass the value in or just not call the custom validator at all if the validation has already failed?  This would save lots of identical code that doesn't actually do anything.  If it's not possible to make this change then the documentation should probably be updated to at least show this.

Tom Christie

unread,
Nov 5, 2012, 5:11:57 AM11/5/12
to django-res...@googlegroups.com
> Would it make sense to either pass the value in...
> ...or just not call the custom validator at all if the validation has already failed?

Absolutely, yes.  One of those two options.
I'm sure there must be a similar case with Form fields and where default validation fails prior to the clean_<field> method being called - what happens in that case?
Let's do the same (or equivalent) thing.

Ian Strachan

unread,
Nov 5, 2012, 6:50:14 AM11/5/12
to django-res...@googlegroups.com
Following the example of the built-in Forms seems like a good idea to me.  I'm not near a computer that I can test this on at the moment but according to the documentation the behaviour is:

As mentioned, any of these methods can raise a ValidationError. For any field, if the Field.clean() method raises a ValidationError, any field-specific cleaning method is not called. However, the cleaning methods for all remaining fields are still executed.

So it sounds like the framework should avoid running the field specific validation function if the field has already failed a previous validation.

Tom Christie

unread,
Nov 5, 2012, 8:00:47 AM11/5/12
to django-res...@googlegroups.com
+1. Also should be noted in the docs on Serializer validation.


Reply all
Reply to author
Forward
0 new messages