I'm trying to implement a simple validator for my POST parameters
My input looks like this:
{
"gage_id": "01010000",
"forcing_source":"my_source",
"forcing_path":"my_path"
}
I have the following Serializer:
class SaveTab1Serializer(Serializer):
gage_id = CharField(min_length=1, required=True),
forcing_source = CharField(min_length=1, required=True),
forcing_path = CharField(min_length=1, required=True),
And I use it like this:
@api_view(['POST'])
def save_tab1(request):
body = json.loads(request.body)
ser = SaveTab1Serializer(data=body)
print('serializer', ser.is_valid())
print('errors', ser.errors)
But no matter what I do with the data, it only shows as valid with no errors. Is there more code that I need to add to the serializer to do the validation?
You have an almost unnoticeable syntax error in your serializer. Serializer fields should be added "stand-alone", you don't need (and shouldn't use) trailing commas. For reasons I don't know, that messes with the serializer's ability to process the fields properly.
Here's a standalone proof of concept:
# test.py
import json
from rest_framework import serializers
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
class SaveTab1Serializer(serializers.Serializer):
gage_id = serializers.CharField(min_length=2, required=True)
forcing_source = serializers.CharField(min_length=2, required=True)
forcing_path = serializers.CharField(min_length=2, required=True)
@api_view(['POST'])
@permission_classes([AllowAny])
def save_tab1(request):
body = json.loads(request.body)
ser = SaveTab1Serializer(data=body)
print('serializer', ser.is_valid())
print('errors', ser.errors)
return Response({ "data": body, "data_is_valid": ser.is_valid(), "data_errors": ser.errors })
# urls.py
path('test/', save_tab1, name='test'),
By comparison, here's the same execution but with trailing commas: