Issue
I'm validating if user that is registering on my website is giving me unique address (city, street, street number etc.) and when it's not unique, then I'm raising serializers.ValidationError
:
class UserSerializer(serializers.ModelSerializer):
def validate(self, attrs):
city = attrs['city']
street = attrs['street']
street_number = attrs['street_number']
apartment_number = attrs['apartment_number'] if 'apartment_number' in attrs else None
unique = check_address_unique(city, street, street_number, apartment_number)
if not unique:
raise serializers.ValidationError(_('Another user has already been registered under this address.'))
return attrs
The problem is that the field name under which the error is passed is this standard non_field_errors
:
{"non_field_errors":["Another user has already been registered under this address."]}
I'd like to somehow give this error a custom name, so the desired output would be:
{"address":["Another user has already been registered under this address."]}
How to accomplish that?
Solution
For single ValidationError you can do it like this:
raise serializers.ValidationError({
'address': _('Another user has already been registered under this address.')
})
If you want to override this name globally, you can use the NON_FIELD_ERRORS_KEY
REST framework setting.
Answered By - dikamilo
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.