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', ) def validate_username(self, username): if not re.search(r'^\w+$', username):
The problem is that when I try to create a user using an existing username, it returns the following dictionary:
{'username': [u'This field must be unique.']}
instead of talking
{'username': [u'Username is already taken']}
I recreated the validate_username function for this (for testing purposes):
def validate_username(self, username): raise serializers.ValidationError('Testing to see if an error is raised.')
and this does not cause an error. Any idea why DjangoRestFramework is ignoring the validate_username function?
Edit: note that I am using ModelSerializer (in the tutorial here: http://www.django-rest-framework.org/api-guide/serializers/#validation it talks about field-level validation only for the Serializer, not the ModelSerializer ) Notice if it matters or not.
source share