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

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

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

9

10 6
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 6
    def validate_empty_values(self, data):
17 6
        (is_empty_value, data) = super(NullFieldMixin, self).validate_empty_values(data)
18 6
        if is_empty_value and data is None:
19 0
            return (False, data)
20 6
        return (is_empty_value, data)
21

22

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

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

31

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

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

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

44

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

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

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

57

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

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

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

Read our documentation on viewing source code .

Loading