dudulu
dudulu

Reputation: 802

Django restframework unique error not processed

When I did not fill in the necessary fields, Django would return a message to the client, but when the field was unique, an error message would appear.

Why didn't Django handle it?

models.py

class UserModel(models.Model):
    email = models.EmailField(unique=True)
    username = models.CharField(max_length=16, blank=True, null=True)
    password = models.CharField(max_length=512)
    is_active = models.BooleanField(default=False)
    sign_up_date = models.DateTimeField(auto_now_add=True)
    sign_in_date = models.DateTimeField(null=True, blank=True)

serializers.py

class UserSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    email = serializers.EmailField()
    username = serializers.CharField(max_length=16)
    password = serializers.CharField(max_length=512)
    is_active = serializers.BooleanField(read_only=True, default=False)
    sign_up_date = serializers.DateTimeField(read_only=True)
    sign_in_date = serializers.DateTimeField(read_only=True)

    class Meta:
        model = UserModel
        fields = (
            'id', 'email', 'username', 'password', 'is_active', 'sign_up_date', 'sign_in_date',)

views.py

class SignupView(CreateAPIView):
    serializer_class = UserSerializer
    queryset = UserModel.objects.all()

error

IntegrityError at /api/signup/
duplicate key value violates unique constraint "User_email_key"
DETAIL:  Key (email)=([email protected]) already exists.

enter image description here

I hope Django can return error messages to the client.

{"email": ["already exists"]}

Upvotes: 1

Views: 459

Answers (1)

AKS
AKS

Reputation: 19801

In the UserSerializer you are declaring some of the model fields again such as email etc. By doing that the behavior of the field is not copied from how it was defined on the model. It works as if that behavior has been overridden.

You can drop email = serializers.EmailField() and then the default behaviour would kick in and you will get to see the error message corresponding to unique field.

In the same fashion you could drop other fields too which are just replicas of the fields on the model.

Upvotes: 1

Related Questions