So I want to create a custom message for the different fail based on the serializer validation. But I was only able to find how to create a standard custom response for success and fail only. Though the only response I want to create is for the failed prompt message.
I found one of the posts but it's not really what I wanted for the error code source: Django Rest Framework custom response message
Basically, the error message must be based on the specific validation error in serializer.py
Here is my code
serializer.py
class UserCreate2Serializer(ModelSerializer):
email = EmailField(label='Email Address')
valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p']
birthTime = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats, allow_null=True, required=False)
class Meta:
model = MyUser
fields = ['username', 'password', 'email', 'first_name', 'last_name', 'gender', 'nric', 'birthday', 'birthTime', 'ethnicGroup']
extra_kwargs = {"password": {"write_only": True}}
def validate(self, data): # to validate if the user have been used
email = data['email']
user_queryset = MyUser.objects.filter(email=email)
if user_queryset.exists():
raise ValidationError("This user has already registered.")
return data
# Custom create function
def create(self, validated_data):
username = validated_data['username']
password = validated_data['password']
email = validated_data['email']
first_name = validated_data['first_name']
last_name = validated_data['last_name']
gender = validated_data['gender']
nric = validated_data['nric']
birthday = validated_data['birthday']
birthTime = validated_data['birthTime']
ethnicGroup = validated_data['ethnicGroup']
user_obj = MyUser(
username = username,
email = email,
first_name = first_name,
last_name = last_name,
gender = gender,
nric = nric,
birthday = birthday,
birthTime = birthTime,
ethnicGroup = ethnicGroup,
)
user_obj.set_password(password)
user_obj.save()
return validated_data
views.py
class CreateUser2View(CreateAPIView):
permission_classes = [AllowAny]
serializer_class = UserCreate2Serializer
queryset = MyUser.objects.all()
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if not serializer.is_valid(raise_exception=False):
return Response({"promptmsg": "You have failed to register an account"}, status=status.HTTP_400_BAD_REQUEST)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response({'promptmsg': 'You have successfully register'}, status=status.HTTP_201_CREATED, headers=headers)
As you can see from serializer validate section, if email exists, it will give an error message of this user has been registered. Same for username but Django has its own validation for it since it is built in.
Is there a way for the error message to be like this: if username is taken, instead of this
"username": [
"A user with that username already exists."
]
to this
"promptmsg": [
"A user with that username already exists."
]
--updated--
models.py
class MyUser(AbstractUser):
userId = models.AutoField(primary_key=True)
gender = models.CharField(max_length=6, blank=True, null=True)
nric = models.CharField(max_length=9, blank=True, null=True)
birthday = models.DateField(blank=True, null=True)
birthTime = models.TimeField(blank=True, null=True)
ethnicGroup = models.CharField(max_length=30, blank=True, null=True)
def __str__(self):
return self.username