Reputation: 802
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?
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)
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',)
class SignupView(CreateAPIView):
serializer_class = UserSerializer
queryset = UserModel.objects.all()
IntegrityError at /api/signup/
duplicate key value violates unique constraint "User_email_key"
DETAIL: Key (email)=([email protected]) already exists.
I hope Django can return error messages to the client.
{"email": ["already exists"]}
Upvotes: 1
Views: 459
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