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?
Custom exception handlingThe exception handler function should either return a Response object, or return None if the exception cannot be handled. If the handler returns None then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.
To check for non-field errors use NON_FIELD_ERRORS as the field parameter. Form. non_field_errors () This method returns the list of errors from Form.
Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
HyperlinkedModelSerializer is a layer of abstraction over the default serializer that allows to quickly create a serializer for a model in Django. Django REST Framework is a wrapper over default Django Framework, basically used to create APIs of various kinds.
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.
Helpful might be this
Here you find all you need to customize your ValidationError output.
For example:
raise ValidationError(
_('Invalid value: %(value)s'),
code='invalid',
params={'value': '42'},
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With