myModel.py 5.49 KB
Newer Older
1
2
3
from django.db import models
from django.contrib.auth.models import User
from rest_framework import serializers
4
5
# from backend.signals import new_revision_saved
# import reversion
6
from django.utils import timezone
7
from backend.models.tools import PendingModeration
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from django.conf import settings
from django.contrib.contenttypes.models import ContentType


class MyModel(models.Model):
    """
        All models in the app deppend of this one !
    """

    moderated_by = models.ForeignKey(
        User, null=True, on_delete=models.SET_NULL, related_name='moderated')
    moderated_on = models.DateTimeField(null=True)

    updated_on = models.DateTimeField(null=True)
    updated_by = models.ForeignKey(
        User, null=True, on_delete=models.SET_NULL, related_name='updated')

    class Meta:
        abstract = True


# class MyModelVersionned(MyModel):
#     class Meta:
#         abstract = True


def is_member(group_name, user):
    return user.groups.filter(name=group_name).exists()


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)
43
44
    moderated_by = serializers.CharField(read_only=True)
    updated_by = serializers.CharField(read_only=True)
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

    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):
        user = self.context['request'].user
        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
                if is_member('Moderator', request.user):
                    return False
                else:
                    return True

        return False

    def set_model_attr_no_moder(self, moderated_and_updated):
        user = self.context['request'].user
        now = timezone.now()
        self.validated_data['moderated_by'] = user
        self.validated_data['moderated_on'] = now

        if moderated_and_updated:
            self.validated_data['updated_by'] = user
            self.validated_data['updated_on'] = now

    def clean_validated_data(self):
        self.validated_data['moderated_by'] = None
        self.validated_data['moderated_on'] = None
        self.validated_data['updated_by'] = None
        self.validated_data['updated_on'] = None

89
90
91
92
93
    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)

94
95
96
97
98
99
100
101
102
103
    def save(self, **kwargs):
        self.clean_validated_data()
        if self.moderation_required():
            print("Modération requise")
            user = self.set_model_attr_for_moder()

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

104
105
            objs_pending_db = self.get_pending_models()
            user = self.context['request'].user
106

107
            self.clean_validated_data()  # Make that it is done...
108
109
            if len(objs_pending_db) > 0:
                pending_instance = objs_pending_db[0]
110
111
                pending_instance.updated_on = timezone.now()
                pending_instance.updated_by = user
112
113
114
115
                pending_instance.new_object = self.validated_data
            else:
                pending_instance = PendingModeration(
                    referenced_object=self.instance,
116
117
                    updated_by=user,
                    updated_on=timezone.now(),
118
119
                    new_object=self.validated_data
                )
120
            pending_instance.save()
121
122
123
124
            return self.instance

        else:
            print("Pas besoin de modération")
125
            moderated_and_updated = True
126
            if self.instance is None:
127
                self.set_model_attr_no_moder(moderated_and_updated)
128
129
130
                return super(MyModelSerializer, self).save(**kwargs)
            else:
                # We check if we don't have any moderation pending
131
                objs_pending_db = self.get_pending_models()
132
                if len(objs_pending_db) > 0:
133
134
135
136
137
138
139
                    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

140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
                    objs_pending_db.delete()

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


# class MyModelVersionnedSerializer(MyModelSerializer):

#     def save(self, **kwargs):
#         user = self.set_model_attr()

#         # Create a revision for the update or creation
#         with reversion.create_revision():
#             super(MyModelVersionnedSerializer, self).save(**kwargs)
#             reversion.set_user(user)

#         # Signal save to perform concat of revisions
#         new_revision_saved.send(sender=self.__class__, obj=self.instance)