1
# Django REST Framework
2 3
from rest_framework import serializers
3

4
# CyBorgBackup
5
# from cyborgbackup.main.fields import *
6

7 3
__all__ = ['BooleanNullField', 'CharNullField', 'ChoiceNullField', 'VerbatimField']
8

9

10 3
class NullFieldMixin(object):
11
    '''
12
    Mixin to prevent shortcutting validation when we want to allow null input,
13
    but coerce the resulting value to another type.
14
    '''
15

16 3
    def validate_empty_values(self, data):
17 3
        (is_empty_value, data) = super(NullFieldMixin, self).validate_empty_values(data)
18 3
        if is_empty_value and data is None:
19 0
            return (False, data)
20 3
        return (is_empty_value, data)
21

22

23 3
class BooleanNullField(NullFieldMixin, serializers.NullBooleanField):
24
    '''
25
    Custom boolean field that allows null and empty string as False values.
26
    '''
27

28 3
    def to_internal_value(self, data):
29 3
        return bool(super(BooleanNullField, self).to_internal_value(data))
30

31

32 3
class CharNullField(NullFieldMixin, serializers.CharField):
33
    '''
34
    Custom char field that allows null as input and coerces to an empty string.
35
    '''
36

37 3
    def __init__(self, **kwargs):
38 3
        kwargs['allow_null'] = True
39 3
        super(CharNullField, self).__init__(**kwargs)
40

41 3
    def to_internal_value(self, data):
42 3
        return super(CharNullField, self).to_internal_value(data or u'')
43

44

45 3
class ChoiceNullField(NullFieldMixin, serializers.ChoiceField):
46
    '''
47
    Custom choice field that allows null as input and coerces to an empty string.
48
    '''
49

50 3
    def __init__(self, **kwargs):
51 3
        kwargs['allow_null'] = True
52 3
        super(ChoiceNullField, self).__init__(**kwargs)
53

54 3
    def to_internal_value(self, data):
55 3
        return super(ChoiceNullField, self).to_internal_value(data or u'')
56

57

58 3
class VerbatimField(serializers.Field):
59
    '''
60
    Custom field that passes the value through without changes.
61
    '''
62

63 3
    def to_internal_value(self, data):
64 0
        return data
65

66 3
    def to_representation(self, value):
67 3
        return value

Read our documentation on viewing source code .

Loading