validateWithRestFramework.py 688 Bytes
Newer Older
1
from rest_framework import serializers
2
3
4
5
6
7
8
9
10
11
12


def validate_with_rest_framework(serializer, value):
    """
        Function to validate some data (comming from JSON)
        against a serializer.
        TODO add test for this...
    """

    valid_ser = serializer(data=value)
    if not valid_ser.is_valid():
13
        raise serializers.ValidationError(str(valid_ser.errors))
14
15
16
17
18
19

    # Also checks that no extra fields were added
    if type(value) is not list:
        allowed_keys = list(valid_ser.get_fields())
        for key in value.keys():
            if key not in allowed_keys:
20
21
                raise serializers.ValidationError(
                    "Expected JSON schema not respected")