16

I would like to show in my template only message that is in string variable, but I don't know how. I am using Django Rest Framework. My code:

form.html

<p>{{ serializer.amount.errors }}</p>

serializers.py

from rest_framework import serializers
from .models import Data, Material


class DataSerializer(serializers.ModelSerializer):

class Meta:
    model = Data
    fields = ('order_date', 'material', 'amount', 'delivery_number', 'employee')
    read_only_fields = ('id', 'insert_time')
    extra_kwargs = {"amount": {"error_messages": {"invalid": "Test Message"}}}

views.py

class Form(APIView):

renderer_classes = [TemplateHTMLRenderer]
template_name = 'zulieferung/form.html'

def get(self, request):
    materials = Material.objects.distinct('material_unit_id')
    return Response({'all_materials': materials})

def post(self, request):
    materials = Material.objects.all()
    serializer = DataSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response({'all_materials': materials}, status=status.HTTP_201_CREATED)
    return Response({'serializer': serializer}, status=status.HTTP_400_BAD_REQUEST)

And instead of Test Message in my template I have [ErrorDetail(string='Test Message', code='invalid')]

enter image description here

mpj
  • 327
  • 1
  • 2
  • 12

6 Answers6

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.'
Manish Shah
  • 331
  • 5
  • 18
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.'
100grams
  • 3,502
  • 3
  • 30
  • 27
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

Community
  • 1
  • 1
Kryštof Řeháček
  • 1,965
  • 1
  • 16
  • 28
  • 1
    Thank you very much! It's working. I will read about forms, I thought that drf would be better for my application. Thanks again! – mpj Aug 29 '18 at 17:18
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.

Shaonsani
  • 178
  • 8
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'
WToloza
  • 11
  • 1
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]
AlexPy
  • 94
  • 7