validation - Django Rest Framework - how to create custom error messages for all ModelSerializer fields? -
this serializers.py (i want create serializer built-in user model):
from rest_framework import serializers django.contrib.auth.models import user class userserializer(serializers.modelserializer): class meta: model = user fields = ('username', 'password', 'email', )
i'm aware django rest framework has it's own field validators, because when try create user using username exists, raises error saying:
{'username': [u'this field must unique.']}
i want customize error message , make "this username taken. please try again" rather saying "this field must unique".
it has built-in regex validator, because when create username exclamation mark, says:
{'username': [u'enter valid username. value may contain letters, numbers , @/./+/-/_ characters.']}
i want customize regex validator says "invalid username".
how customize of error messages each field has?
note: according post: custom error messages in django rest framework serializer can do:
class userserializer(serializers.modelserializer): class meta: model = user def __init__(self, *args, **kwargs): super(userserializer, self).__init__(*args, **kwargs) self.fields['username'].error_messages['required'] = u'my custom required msg'
but do 'unique' , 'regex' validators? tried doing
self.fields['username'].error_messages['regex'] = u'my custom required msg'
and
self.fields['username'].error_messages['validators'] = u'my custom required msg'
but neither worked.
in order replace unique or regex error messages should change message
member of corresponding validator object. done using separate mixin class:
from django.core.validators import regexvalidator rest_framework.validators import uniquevalidator django.utils.translation import ugettext_lazy _ class setcustomerrormessagesmixin: """ replaces built-in validator messages messages, defined in meta class. mixin should inherited before actual serializer class in order call __init__ method. example of meta class: >>> class meta: >>> model = user >>> fields = ('url', 'username', 'email', 'groups') >>> custom_error_messages_for_validators = { >>> 'username': { >>> uniquevalidator: _('this username taken. please, try again'), >>> regexvalidator: _('invalid username') >>> } >>> } """ def __init__(self, *args, **kwargs): # noinspection pyargumentlist super(setcustomerrormessagesmixin, self).__init__(*args, **kwargs) self.replace_validators_messages() def replace_validators_messages(self): field_name, validators_lookup in self.custom_error_messages_for_validators.items(): # noinspection pyunresolvedreferences validator in self.fields[field_name].validators: if type(validator) in validators_lookup: validator.message = validators_lookup[type(validator)] @property def custom_error_messages_for_validators(self): meta = getattr(self, 'meta', none) return getattr(meta, 'custom_error_messages_for_validators', {})
then inherit mixin , update meta
class:
class userserializer(setcustomerrormessagesmixin, serializers.hyperlinkedmodelserializer): class meta: model = user fields = ('url', 'username', 'email', 'groups') custom_error_messages_for_validators = { 'username': { uniquevalidator: _('this username taken. please, try again'), regexvalidator: _('invalid username') } }
Comments
Post a Comment