Chetan Shelake
Chetan Shelake

Reputation: 686

Django rest framework get validation error object in detail

[ErrorDetail(string='This field is required.', code='required')]

How get code from this object. I want separate error code for custom error response, i tried many solutions but i didn't get any working answer.

Upvotes: 7

Views: 3583

Answers (1)

msonsona
msonsona

Reputation: 1311

I found myself wanting to read the string field of the Error.

So for an error like:

<Response status_code=400, "application/json"> 
{'field_name': [ErrorDetail(string='the error message', code='invalid')]}

To get the string (e.g. for testing), I've used:

self.assertEqual(str(response.data['field_name'][0]), 'the error message')

Upvotes: 9

Related Questions