validateWithRestFramework.py 655 Bytes
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from django.core.exceptions import ValidationError


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():
        raise ValidationError(str(valid_ser.errors))

    # 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:
                raise ValidationError("Expected JSON schema not respected")