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')]
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.'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With