I have Administrator module extended from default Django User module.
In Django Rest Framework, I create a serializer for this module with username and email validators.
Everything go well when I declare validators inlined:
class AdministratorCreateUpdateSerializer(ModelSerializer):
username = serializers.CharField(
source='user.username',
validators=[UniqueValidator(queryset=User.objects.all())]
)
email = serializers.EmailField(
source='user.email',
validators=[UniqueValidator(queryset=User.objects.all())]
)
password = serializers.CharField(
source='user.password',
allow_blank=True,
style={'input_type': 'password'}
)
first_name = serializers.CharField(
source='user.first_name'
)
last_name = serializers.CharField(
source='user.last_name'
)
class Meta:
model = Administrator
fields = [
'username',
'email',
'password',
'first_name',
'last_name',
]
But the validators not execute when I declare it inside extra_kwargs
:
class AdministratorCreateUpdateSerializer(ModelSerializer):
username = serializers.CharField(
source='user.username',
)
email = serializers.EmailField(
source='user.email',
)
password = serializers.CharField(
source='user.password',
allow_blank=True,
style={'input_type': 'password'}
)
first_name = serializers.CharField(
source='user.first_name'
)
last_name = serializers.CharField(
source='user.last_name'
)
class Meta:
model = Administrator
fields = [
'username',
'email',
'password',
'first_name',
'last_name',
]
extra_kwargs = {
'username': {
'validators': [UniqueValidator(queryset=User.objects.all())]
},
'email': {
'validators': [UniqueValidator(queryset=User.objects.all())]
},
}
Does this problem come from using source
when define addition fields or something else?
extra_kwargs
do not work for fields which are explicitly declared on the serializer. It's the same case with read_only_fields
, which are then passed to extra_kwargs
. Each field that's declared explicitly is simply omitted when extra_kwargs
are added to the rest of the constructor arguments.
This should be clearly pointed out in the docs but it's not.
discussion: https://github.com/encode/django-rest-framework/issues/3460
code: https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py#L1007
so your first solution is the only proper solution :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With