How to validate a json object in django

Nayan picture Nayan · May 20, 2017 · Viewed 10.2k times · Source

I'm submitting a JSON to a django view with AJAX. The JSON looks like the following:

{
   "code":"9910203040", // required
   "name":"Abc", // required
   "payments":[
      {
         "amount":300, // required
         "name":"efg", // required,
         "type": 2 // can be empty
      },
      {
         "amount":100,
         "name":"pqr",
         "type": 3
      }
   ]
}

The payments list can be of any size. How can I validate this in Django? Is it possible to use Django Forms to validate this? If it was Spring, I would create Request classes and use annotations on fields but can't figure out how to do this in Django.

Answer

tom picture tom · May 20, 2017

You can use django rest framework to validate request data as mentioned by @zaphod100.10 ,

here is the serializer you can use to validate-

from rest_framework import serializers

class PaymentSerializer(serializers.Serializer):
    amount = serializers.IntegerField(required=True, min_value=0, null=True)
    name = serializers.CharField(required=True, max_length=128)
    type = serializers.IntegerField(required=True, min_value=0)

class ValidateFormSerializer(serializers.Serializer):
    code = serializers.CharField(required=True, max_length=32)
    name = serializers.CharField(required=True, max_length=128)
    payments = serializers.ListField(child=PaymentSerializer)

You need like this to validate it in the view section -

 import ValidateFormSerializer

# add this snippet in your view section
 valid_ser = ValidateFormSerializer(data=request.data)
 if valid_ser.is_valid():
       post_data = valid_ser.validated_data
 else:
      print(valid_ser.errors)

Let me know, if it is enough to solve your problem.