usefullLinksField.py 1.11 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
from django.contrib.postgres.fields import JSONField
from django.core.exceptions import ValidationError

from rest_framework import serializers
from rex.models.tools.validateWithRestFramework import validate_with_rest_framework


class UrlAndDescriptionSerializer(serializers.Serializer):
    """
        Simple serialize used to validate each usefull links objs
    """
    url = serializers.URLField(required=True)
    description = serializers.CharField(
        required=False, allow_null=True, allow_blank=True)


def validate_usefull_links(value):
    """
        Function validate the data that should be stored
        in a usefull_links field
    """

    if type(value) is not list:
        raise ValidationError("Usefull links must be a JSON array !")

    for obj in value:
        validate_with_rest_framework(UrlAndDescriptionSerializer, obj)


class UsefullLinksField(JSONField):
    description = "A field to store a URL and a description as single JSON data"

    def __init__(self, *args, **kwargs):
        kwargs['validators'] = [validate_usefull_links]
        super(UsefullLinksField, self).__init__(*args, **kwargs)