2👍
✅
Try adding this code
create or update in views
if User.objects.filter(email=self.request.data['email']).exists():
return Response({"error": "This email id already exists."})
2👍
You could try raising a ValidationError
which is part of the serializers
library:
from rest_framework import serializers
def update(self, instance, validated_data):
# If `self.request.data["email"]` works
if User.objects.filter(email=self.request.data["email"]).exists():
raise serializers.ValidationError("This email already exists.")
# If `self.request.data["email"]` doesn't work
new_email = self.initial_data.get("email"):
if new_email and User.objects.filter(email=new_email).exists():
raise serializers.ValidationError("This email already exists.")
# Save and return the modified instanced
or if you unique=True
to the email
field, it will raise an IntegrityError
so you don’t need to do any further checks. You simply catch the error and handle it yourself.
- [Django]-Why is uWSGI using more memory than Apache?
- [Django]-AttributeError: 'module' object has no attribute 'Datefield'
1👍
I assume you want email
to be unique. Then you should add unique=True
to your user model’s email field.
class YourUserModel(AbstractUser):
email = models.EmailField(unique=True)
After you make email a unique field, your database will not allow to add another entry with the same email and it will raise IntegrityError
. You can catch this error and return a better error message to your user. Like this:
try:
if serializer.is_valid(raise_exception=False):
serializer.save()
except IntegrityError:
return Response(data={'message':'that email is in use'}, status=HTTP_400_BAD_REQUEST)
- [Django]-How can I do AND lookups with Q objects when using repeated arguments instead of chaining filters?
- [Django]-What is different between `request.data['param-name'] ` or `request.data.get('param-name')` in Django
- [Django]-How to change model class name without losing data?
- [Django]-Object has no attribute 'get_absolute_url'
- [Django]-Python/Django: RelatedObjectDoesNotExist: Cart has no user
Source:stackexchange.com