Issue
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')]
Solution
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:
Answered By - Kryštof Řeháček
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.