Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django REST framework, validate json data

The server comes with json format:

{
    "type": "string",
    "object": {
        "lead_id": int,
        "form_name": "string",
        "answers": [
            {
                "lead_id": int,
                "key": "string",
            }
            ...
        ]
    },
    "group_id": int,
    "secret": "string"
}

How to use django REST framework to validate this json?

ru version

like image 750
devnull Avatar asked Sep 04 '18 13:09

devnull


3 Answers

You can use django rest framework to write you own validators like so,

class MultipleOf(object):
   def __init__(self, base):
       self.base = base

   def __call__(self, value):
       if value % self.base != 0:
           message = 'This field must be a multiple of %d.' % self.base
           raise serializers.ValidationError(message)

You can find more details here

Hope this helps!

like image 78
devdob Avatar answered Sep 19 '22 17:09

devdob


Example:

# serializers.py
from rest_framework import serializers


class VkObjectSerializer(serializers.Serializer):
    """
    is 'object'
    """
    lead_id = serializers.IntegerField()
    group_id = serializers.IntegerField()
    user_id = serializers.IntegerField()
    form_id = serializers.IntegerField()


class VkBaseSerializer(serializers.Serializer):
    """
    Base serializer 
    """
    type = serializers.CharField(max_length=200)

    object = VkObjectSerializer()

    group_id = serializers.IntegerField()
    secret = serializers.CharField(max_length=200)

# view.py
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from .serializers import VkBaseSerializer


class VkCallbackView(CreateAPIView):
    serializer_class = VkBaseSerializer

    def create(self, request, *args, **kwargs):
        """
        Method is validate json in view
        """
        valid_ser = self.serializer_class(data=request.data)
        if valid_ser.is_valid():
            return Response('True')
        return Response('False')

Valid data:

>>> valid_ser.data
{
    "type": "str",
    "object": {
        "lead_id": 123,
        "group_id": 12345,
        "user_id": 12352,
        "form_id": 1
    },
    "group_id": 5123,
    "secret": "str"
}

The answers were very helpful:

  • Django Rest Framework ListField and DictField - how to set model json
  • How to validate a json object in django - validate data in view
like image 2
devnull Avatar answered Oct 19 '22 23:10

devnull


class AnswersSerializer(serializers.Serializer):
    lead_id = serializers.IntegerField(required=True)
    key = serializers.CharField(max_length=100)

class ObjectSerializer(serializers.Serializer):
    lead_id = serializers.IntegerField(required=True)
    form_name = serializers.CharField(max_length=100)
    answers = serializers.ListField(child=AnswersSerializer())

class UpdateGroup(serializers.Serializer):
    group_id = serializers.IntegerField(required=True)
    type = serializers.CharField(max_length=100)
    secret = serializers.CharField(max_length=100)
    object = serializers.DictField(child=, default={})
like image 2
Niraj Panchasara Avatar answered Oct 20 '22 00:10

Niraj Panchasara