universitySemestersDates.py 2.13 KB
Newer Older
Florent Chehab's avatar
Florent Chehab committed
1
from django.db import models
2
3
from backend.models.module import BasicModule, BasicModuleSerializer
from backend.models.university import University
Florent Chehab's avatar
Florent Chehab committed
4
5
6
7
8
9
10
11
12
13
14
15
16
from rest_framework import serializers, viewsets, permissions


def check_nones(val1, val2):
    if val1 is None and val2 is not None:
        raise serializers.ValidationError("Check your dates")

    if val2 is None and val1 is not None:
        raise serializers.ValidationError("Check your dates")

    return val1 is None and val2 is None


17
class UniversitySemestersDates(BasicModule):
Florent Chehab's avatar
Florent Chehab committed
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
43

    university = models.OneToOneField(
        University, on_delete=models.CASCADE, related_name='university_semesters_dates', primary_key=True, null=False)

    spring_begin = models.DateField(null=True, blank=True)
    spring_end = models.DateField(null=True, blank=True)
    autumn_begin = models.DateField(null=True, blank=True)
    autumn_end = models.DateField(null=True, blank=True)

    # Need custom validation

    # TODO add tests
    def clean(self, *args, **kwargs):
        spring_ok = check_nones(self.spring_begin, self.spring_end)
        autumn_ok = check_nones(self.autumn_begin, self.autumn_end)

        if not spring_ok:
            spring_ok = self.spring_begin < self.spring_end

        if not autumn_ok:
            autumn_ok = self.autumn_begin < self.autumn_end
        # no check if spring_end < autumn_begin in case info is not available

        if not (spring_ok and autumn_ok):
            print("ici")
            raise serializers.ValidationError("Check your dates !")
44
        super(UniversitySemestersDates, self).clean(*args, **kwargs)
Florent Chehab's avatar
Florent Chehab committed
45
46
47

    def save(self, *args, **kwargs):
        self.full_clean()
48
        super(UniversitySemestersDates, self).save(*args, **kwargs)
Florent Chehab's avatar
Florent Chehab committed
49
50


51
class UniversitySemestersDatesSerializer(BasicModuleSerializer):
Florent Chehab's avatar
Florent Chehab committed
52
53

    class Meta:
54
        model = UniversitySemestersDates
Florent Chehab's avatar
Florent Chehab committed
55
        fields = '__all__'
Florent Chehab's avatar
Florent Chehab committed
56
57


58
class UniversitySemestersDatesViewSet(viewsets.ModelViewSet):  # TODO switch to dict
Florent Chehab's avatar
Florent Chehab committed
59
    permission_classes = (permissions.DjangoModelPermissions,)
60
61
    queryset = UniversitySemestersDates.objects.all()  # pylint: disable=E1101
    serializer_class = UniversitySemestersDatesSerializer