Ahmed  Samy
Ahmed Samy

Reputation: 53

drf ModelSerializer field level validation

I'm trying to Field-Level validation to validate branch field in ModelSerialzer but this method never called.

class UserProfileSerializer(serializers.ModelSerializer):
    branch = serializers.ChoiceField(choices=Branch.choices)

    class Meta:
        model = UserProfile
        exclude = ['user']

    def validate_branch(self, branch):
        print(branch)
        return branch.upper()


class CustomRegisterSerializer(RegisterSerializer):
    profile = UserProfileSerializer(source="userprofile")

    @transaction.atomic
    def create(self, validated_data):
        validated_profile_data = validated_data.pop('profile')
        user = User.objects.create(**validated_data)
        UserProfile.objects.create(user=user, **validated_profile_data)
        return user

I followed this drf docs.

Upvotes: 0

Views: 192

Answers (1)

Hasidul Islam
Hasidul Islam

Reputation: 416

The validators are run when is_valid is called. You can get some idea from the code mentioned below on how to call the is_valid() method. You can call it from views.py.

serializer = UserProfileSerializer(data="The data you want to send")
serializer.is_valid(raise_exception=True)

Upvotes: 1

Related Questions