Django Rest Framework - how to create custom error messages for all ModelSerializer fields?

This is my serializers.py (I want to create a serializer for the built-in User model):

from rest_framework import serializers from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password', 'email', ) 

I know that the Django Rest Framework has its own field checks, because when I try to create a user using a username that already exists, an error occurs:

 {'username': [u'This field must be unique.']} 

I want to customize the error message and make it say, "This username has already been completed. Please try again," rather than "This field must be unique."

It also has a built-in regular expression validator, because when I create a user name with an exclamation mark, it says:

 {'username': [u'Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.']} 

I want to configure the regex validator to just say "Invalid username."

How to configure all error messages that each field has?

Note: according to this post: Custom error messages in the Django Rest Framework serializer I 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 what should I do for the 'unique' and 'regex' validators? I tried to do

 self.fields['username'].error_messages['regex'] = u'My custom required msg' 

and

 self.fields['username'].error_messages['validators'] = u'My custom required msg' 

but not one of them worked.

+6
source share
1 answer

To replace error messages with a unique or regular expression, you must change the message member of the corresponding validation object. This can be done using a separate mixin class:

 from django.core.validators import RegexValidator from rest_framework.validators import UniqueValidator from django.utils.translation import ugettext_lazy as _ class SetCustomErrorMessagesMixin: """ Replaces built-in validator messages with messages, defined in Meta class. This mixin should be inherited before the actual Serializer class in order to 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 is already 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): for field_name, validators_lookup in self.custom_error_messages_for_validators.items(): # noinspection PyUnresolvedReferences for 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 you can simply inherit this mixin and update the 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 is already taken. Please, try again'), RegexValidator: _('Invalid username') } } 
+5
source

Source: https://habr.com/ru/post/988287/


All Articles