Aah, I didn't think about updating the validators after calling 
super().__init__, that's much nicer, thanks!

On Monday, 11 September 2017 12:02:10 UTC+1, Xavier Ordoquy wrote:
>
> Hi,
>
> DRF fields adds the validators during the init rather than setting them on 
> Meta.
> That help with heritage.
>
> You can see how this works at 
> https://github.com/encode/django-rest-framework/blob/master/rest_framework/fields.py#L799-L802
>
> Hope this helps,
> Regards,
> Xavier Ordoquy,
> Linovia.
>
> Le 11 sept. 2017 à 12:54, phi...@futrli.com <javascript:> a écrit :
>
> Hi all,
>
> I'm trying to add a list of validators to a subclass of 
> rest_framework.fields.Field.
> I would prefer to add the validators to the field declaration, rather than 
> every place it is used.
>
> Ideally, I would like to be able to declare the Field similarly a 
> Serializer, e.g:
>
> class MyField(rest_framework.fields.Field):
>     class Meta:
>         validators = (
>             my_validation_function,
>         )
>
> However, it looks like the Meta class is only used in subclasses of 
> Serializer, and not in subclasses of Field.
>
>
> Adding the validators during __init__ is pretty ugly:
>
> class MyField(rest_framework.fields.Field):
>     def __init__(self, read_only=False, write_only=False, required=None, 
> default=empty, initial=empty, source=None,
>                  label=None, help_text=None, style=None, 
> error_messages=None, validators=None, **kwargs):
>         if validators is None:
>             validators = []
>         else:
>             validators = list(validators)
>         default_validators = (
>             my_validator,
>         )
>         validators.extend(default_validators)
>         super().__init__(read_only, write_only, required, default, 
> initial, source, label, help_text, style,
>                          error_messages, validators, **kwargs)
>
>
> Is there a better way to add a list of validators to a field inside the 
> declaration of the field?
>
> Thanks in advance for any help,
> Phil Woods
>
> -- 
> You received this message because you are subscribed to the Google Groups 
> "Django REST framework" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to django-rest-framework+unsubscr...@googlegroups.com <javascript:>.
> For more options, visit https://groups.google.com/d/optout.
>
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-rest-framework+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to