Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 665
mpj Avatar asked Aug 29 '18 14:08

mpj


1 Answers

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.'
like image 71
Manish Shah Avatar answered Sep 22 '22 01:09

Manish Shah