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'm aware that Django Rest Framework has it's own field validators, because when I try to create a user using a username which already exists, it raises an error saying:
{'username': [u'This field must be unique.']}
I want to customize the error message and make it say "This username is already taken. Please try again" rather than saying "This field must be unique".
It also has a built-in regex validator, because when I create a username with an exclamation mark, it says:
{'username': [u'Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.']}
I want to customize the regex validator so that it just says "Invalid username".
How do I customize all of the error messages which each field has?
Note: according to this post: Custom error messages in 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 do I do for the 'unique' and 'regex' validators? I 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.