myModelSerializer.py 4.66 KB
Newer Older
1
2
from rest_framework import serializers
from django.utils import timezone
3
from .pendingModeration import PendingModeration
4
5
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
6
from backend.utils import is_member
Florent Chehab's avatar
Florent Chehab committed
7
from .myModel import MyModel
8
9
10
11
12
13
14


class MyModelSerializer(serializers.ModelSerializer):
    moderated_on = serializers.DateTimeField(
        format="%Y-%m-%d %H:%M:%S", read_only=True)
    updated_on = serializers.DateTimeField(
        format="%Y-%m-%d %H:%M:%S", read_only=True)
15
16
    moderated_by = serializers.CharField(read_only=True)
    updated_by = serializers.CharField(read_only=True)
17

Florent Chehab's avatar
Florent Chehab committed
18
    # TODO : updated_by_username useless ? See in rest API
19
20
21
22
23
24
25
26
27
28
29
30
    updated_by_username = serializers.SerializerMethodField(read_only=True)

    def get_updated_by_username(self, obj):
        if obj.updated_by:
            return obj.updated_by.username
        else:
            return None

    class Meta:
        model = MyModel

    def moderation_required(self):
Florent Chehab's avatar
Florent Chehab committed
31
32
33
        if hasattr(self.Meta, 'NEVER_MODERATE') and self.Meta.NEVER_MODERATE:
            return False

34
        user = self.get_user_in_request()
35
36
37
38
39
40
41
        request = self.context['request']

        if user.is_staff:
            return False

        if settings.MODERATION_ACTIVATED:
            if request.method in ['POST', 'PUT']:  # should be always the case
42
                return not is_member('Moderators', request.user)
43
44
45

        return False

46
47
48
    def get_user_in_request(self):
        return self.context['request'].user

49
    def set_model_attr_no_moder(self, moderated_and_updated):
50
        user = self.get_user_in_request()
51
        now = timezone.now()
Florent Chehab's avatar
Florent Chehab committed
52
53
54
55
        self.override_validated_data({
            'moderated_by': user,
            'moderated_on': now,
        })
56
57

        if moderated_and_updated:
Florent Chehab's avatar
Florent Chehab committed
58
59
60
61
            self.override_validated_data({
                'updated_by': user,
                'updated_on': now,
            })
62
63

    def clean_validated_data(self):
Florent Chehab's avatar
Florent Chehab committed
64
65
66
67
68
69
        self.override_validated_data({
            'moderated_by': None,
            'moderated_on': None,
            'updated_by': None,
            'updated_on': None,
        })
70

71
72
73
74
75
    def get_pending_models(self):
        ct = ContentType.objects.get_for_model(self.Meta.model)
        return PendingModeration.objects.filter(
            content_type=ct, object_id=self.instance.pk)

Florent Chehab's avatar
Florent Chehab committed
76
77
78
79
80
81
82
83
84
85
    def override_validated_data(self, new_data):
        """
        Method used to force specific attributes when saving a model
        """
        for key in new_data:
            self.validated_data[key] = new_data[key]

    def my_pre_save(self):
        pass

86
    def save(self, **kwargs):
87
        user = self.get_user_in_request()
88
        self.clean_validated_data()
Florent Chehab's avatar
Florent Chehab committed
89
        self.my_pre_save()
90

91
92
93
94
95
        if self.moderation_required():
            if self.instance is None:  # we need to create the main model
                self.instance = super(
                    MyModelSerializer, self).save(**kwargs)

96
            objs_pending_db = self.get_pending_models()
97

98
            self.clean_validated_data()  # Make that it is done...
99
100
            if len(objs_pending_db) > 0:
                pending_instance = objs_pending_db[0]
101
102
                pending_instance.updated_on = timezone.now()
                pending_instance.updated_by = user
103
104
105
106
                pending_instance.new_object = self.validated_data
            else:
                pending_instance = PendingModeration(
                    referenced_object=self.instance,
107
108
                    updated_by=user,
                    updated_on=timezone.now(),
109
110
                    new_object=self.validated_data
                )
111
            pending_instance.save()
112
113
114
            return self.instance

        else:
115

116
            moderated_and_updated = True
117
            if self.instance is None:
118
                self.set_model_attr_no_moder(moderated_and_updated)
119
120
121
                return super(MyModelSerializer, self).save(**kwargs)
            else:
                # We check if we don't have any moderation pending
122
                objs_pending_db = self.get_pending_models()
123
                if len(objs_pending_db) > 0:
124
125
126
127
128
129
130
                    obj_pending_db = objs_pending_db[0]
                    self.clean_validated_data()  # Make that it is done...
                    if obj_pending_db.new_object == self.validated_data:
                        moderated_and_updated = False
                        self.validated_data['updated_by'] = obj_pending_db.updated_by
                        self.validated_data['updated_on'] = obj_pending_db.updated_on

131
132
                    objs_pending_db.delete()

133
134
                self.set_model_attr_no_moder(moderated_and_updated)
                return super(MyModelSerializer, self).save(**kwargs)