DjangoRestFramework ModelSerializer: field level check not working

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): #checks if all the characters in username are in the regex. If they aren't, it returns None raise serializers.ValidationError('Username can only contain alphanumeric characters and the underscore.') try: User.objects.get(username=username) except ObjectDoesNotExist: return username raise serializers.ValidationError('Username is already taken.') 

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.

+2
source share
1 answer

Field-level checking is called before checking the serialization level.

So, a User model having a username as unique=True , field-level checking will throw an exception because the username is already present. DRF UniqueValidator does this job of collecting exceptions when the field is not unique.

According to the DRF source code,

 class UniqueValidator: """ Validator that corresponds to `unique=True` on a model field. Should be applied to an individual field on the serializer. """ message = _('This field must be unique.') 

Since these validators are executed before being verified at the serialization level, your validate_username never called.

+2
source

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


All Articles