1ce83cc3e00f6ae0e4412218c1865c0aebeaad9b
[wolnelektury.git] / src / api / fields.py
1 from rest_framework import serializers
2 from django.core.urlresolvers import reverse
3 from paypal.rest import user_is_subscribed
4
5
6 class AbsoluteURLField(serializers.ReadOnlyField):
7     def __init__(self, view_name=None, view_args=None, source='get_absolute_url', *args, **kwargs):
8         if view_name is not None:
9             source = '*'
10         super(AbsoluteURLField, self).__init__(*args, source=source, **kwargs)
11         self.view_name = view_name
12         self.view_args = {}
13         if view_args:
14             for v in view_args:
15                 fields = v.split(':', 1)
16                 self.view_args[fields[0]] = fields[1] if len(fields)>1 else fields[0]
17
18     def to_representation(self, value):
19         if self.view_name is not None:
20             kwargs = {
21                 arg: getattr(value, field)
22                 for (arg, field) in self.view_args.items()
23             }
24             value = reverse(self.view_name, kwargs=kwargs)
25         return self.context['request'].build_absolute_uri(value)
26
27
28 class LegacyMixin(object):
29     def to_representation(self, value):
30         value = super(LegacyMixin, self).to_representation(value)
31         non_null_fields = getattr(getattr(self, 'Meta', None), 'legacy_non_null_fields', [])
32         for field in non_null_fields:
33             if field in value and value[field] is None:
34                 value[field] = ''
35         return value
36
37
38 class UserPremiumField(serializers.ReadOnlyField):
39     def __init__(self, *args, **kwargs):
40         super(UserPremiumField, self).__init__(*args, source='*', **kwargs)
41
42     def to_representation(self, value):
43         return user_is_subscribed(value)