myModel.py 1.72 KB
Newer Older
Florent Chehab's avatar
Florent Chehab committed
1
from django.contrib.auth.models import User
Florent Chehab's avatar
Florent Chehab committed
2
from django.contrib.contenttypes.fields import GenericRelation
Florent Chehab's avatar
Florent Chehab committed
3
from django.core.exceptions import ValidationError
Florent Chehab's avatar
Florent Chehab committed
4
5
6
7
8
9
from django.core.validators import MinValueValidator
from django.db import models

from shared import DEFAULT_OBJ_MODERATION_LV, OBJ_MODERATION_PERMISSIONS

from .pendingModeration import PendingModeration
Florent Chehab's avatar
Florent Chehab committed
10

11
12
13
POSSIBLE_OBJ_MODER_LV = [
    OBJ_MODERATION_PERMISSIONS[key] for key in OBJ_MODERATION_PERMISSIONS
]
Florent Chehab's avatar
Florent Chehab committed
14
15
16
17


def validate_obj_model_lv(value):
    if value not in POSSIBLE_OBJ_MODER_LV:
18
        raise ValidationError("obj_moderation_level not recognized")
Florent Chehab's avatar
Florent Chehab committed
19
20
21
22
23


class MyModel(models.Model):
    """
        All models in the app deppend of this one.
Florent Chehab's avatar
Florent Chehab committed
24
        It contains the required attributes for managing optionnal data moderation.
Florent Chehab's avatar
Florent Chehab committed
25
26
27
28

        All the logic behind moderation is done in myModelSerializer
    """

Florent Chehab's avatar
Florent Chehab committed
29
30
    # store the update author
    updated_by = models.ForeignKey(
31
32
        User, null=True, on_delete=models.SET_NULL, related_name="+"
    )
Florent Chehab's avatar
Florent Chehab committed
33
    # store the update date (model can be updated without moderation)
Florent Chehab's avatar
Florent Chehab committed
34
    updated_on = models.DateTimeField(null=True)
Florent Chehab's avatar
Florent Chehab committed
35
36
37

    # store the moderator
    moderated_by = models.ForeignKey(
38
39
        User, null=True, on_delete=models.SET_NULL, related_name="+"
    )
Florent Chehab's avatar
Florent Chehab committed
40
41
42
43
    # store the moderation date
    moderated_on = models.DateTimeField(null=True)

    # Store the object moderation level by default
Florent Chehab's avatar
Florent Chehab committed
44
    obj_moderation_level = models.SmallIntegerField(
Florent Chehab's avatar
Florent Chehab committed
45
46
        default=DEFAULT_OBJ_MODERATION_LV,
        validators=[MinValueValidator(0), validate_obj_model_lv],
47
    )
Florent Chehab's avatar
Florent Chehab committed
48
    # Add the link to pending moderation
Florent Chehab's avatar
Florent Chehab committed
49
    pending_moderation = GenericRelation(PendingModeration)
Florent Chehab's avatar
Florent Chehab committed
50
51
52

    class Meta:
        abstract = True
53

54
    model_config = {"moderation_level": None}