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.
The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.
JSON Schema is a powerful tool. It enables you to validate your JSON structure and make sure it meets the required API. You can create a schema as complex and nested as you need, all you need are the requirements. You can add it to your code as an additional test or in run-time.
JSON Validator verifies that your JavaScript Object Notation adheres to the JSON specification: www.json.org. JSON Validator also formats or humanizes your JSON to render it readable following common linting practices such as multi-line and indentation.
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.
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