Confirmation codes and messages in the Django Rest Framework

Using the field fields in the serializer, validation error messages look something like this:

{ "product": [ "This field must be unique." ], "price": [ "This field is required." ] } 

However, for the API I am writing, I would like to provide a unique error code for each failed check so that clients can programmatically respond to check errors or can provide their own user messages in the user interface. Ideally, a json error would look something like this:

 { "product": [ { "code": "unique", "message": "This field must be unique." } ], "price": [ { "code": "required", "message": "This field is required." } ] } 

The current approach using ValidationErrors makes this pretty complicated. Looking through the code, it seems that this type of error message is not currently supported. However, I am looking for an approach to redefine error handling according to this model.

+5
source share
1 answer

Add something like this to your serializer:

 def is_valid(self, raise_exception=False): try: return super(ClientSerializer, self).is_valid(raise_exception) except exceptions.ValidationError as e: if 'email' in e.detail: for i in range(len(e.detail['email'])): if e.detail['email'][i] == UniqueValidator.message: e.detail['email'][i] = {'code': 'not-unique'} raise e 
+1
source

Source: https://habr.com/ru/post/1211942/


All Articles