[Fixed]-Django extract string from [ErrorDetail(string='Test Message', code='invalid')]

4👍

You should try in your template

{% for error in serializer.amount.errors %}
    {{ error }}
{% endofor %}

But I do not understand why do you use django rest_framework with HTML templates. Rest framework is used for REST APIs which is definitely not this case. For this purpose use rather django.forms. It really does not make sense to use REST serializer directly rendered to the HTML template.

Links:

Working with forms

When to use REST framework

12👍

You can get the string from the ErrorDetail Object in this way:-

>>> op = ErrorDetail(string='Value must be valid JSON or key, valued pair.', code='invalid')
>>> op.title()
'Value must be valid JSON or key, valued pair.'

5👍

>>> error = ErrorDetail(string='Value must be valid JSON or key, valued pair.', code='invalid')
>>> str(error)
'Value must be valid JSON or key, valued pair.'

1👍

As the serializer’s errors are in a list, so you have to handle it more preciously,
I put a very straight forward and intuitive solution to get the string value from the object.

for key, values in serializers.errors.items():
   error = [value[:] for value in values]
   print(error)

Then you can get all error in a list. Though fields has multiple errors in list. so my code can extract string from ErrorDetail() objects.

1👍

I was testing one invalid serializer data, when i haved this problem, check:

{"key": [ErrorDetail(string='Test Message', code='invalid')]}

This ErrorDetail is <class ‘rest_framework.exceptions.ErrorDetail’>
DRF class ErrorDetail
when you find attrs of this class you can check code

class ErrorDetail(str):
"""
A string-like object that can additionally have a code.
"""
code = None

def __new__(cls, string, code=None):
    self = super().__new__(cls, string)
    self.code = code
    return self

You can access to code like regular object, like this:

response.data['key'][0].code #'invalid'

0👍

You can get the error message from rest_framework.exceptions.ValidationError object as follows

err = ErrorDetail(string='User with the given Email exists', code='invalid')
err_message = err.args[0]

Leave a comment