usefullLinksField.py 1.12 KB
Newer Older
1 2
from django.contrib.postgres.fields import JSONField
from rest_framework import serializers
3
from backend.models.tools.validateWithRestFramework import validate_with_rest_framework
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21


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:
22 23
        raise serializers.ValidationError(
            "Usefull links must be a JSON array !")
24 25 26 27 28 29 30 31 32 33

    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]
Florent Chehab's avatar
Florent Chehab committed
34
        kwargs['default'] = list
35
        super(UsefullLinksField, self).__init__(*args, **kwargs)