Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework: how to set a custom name form non_field_errors?

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?

like image 791
Marek M. Avatar asked Oct 23 '16 12:10

Marek M.


People also ask

How do I create a custom exception in Django REST framework?

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.

What is form Non_field_errors?

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.

Why do we use Serializers in Django REST framework?

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.

What is HyperlinkedModelSerializer?

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.


2 Answers

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.

like image 191
dikamilo Avatar answered Sep 28 '22 02:09

dikamilo


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'},
)
like image 34
zypro Avatar answered Sep 28 '22 04:09

zypro