userData.py 1.51 KB
Newer Older
1
from django.db import models
Florent Chehab's avatar
Florent Chehab committed
2
3
from rest_framework import permissions, serializers
from backend.models.university import University
4
from django.contrib.postgres.fields import JSONField
Florent Chehab's avatar
Florent Chehab committed
5
6
7
from backend.models.my_model import MyModel, MyModelSerializer, MyModelViewSet
from django.contrib.auth.models import User
from backend.models.tools import NoDelete, IsOwner
8
9


Florent Chehab's avatar
Florent Chehab committed
10
11
12
class UserData(MyModel):
    owner = models.OneToOneField(User, on_delete=models.CASCADE)
    contact_info = JSONField(null=True, default={})
13
14
    contact_info_is_public = models.BooleanField(default=False)
    config = JSONField(null=True, default={})
Florent Chehab's avatar
Florent Chehab committed
15
16
    black_list = models.ManyToManyField(
        University, related_name='+', blank=True)
17
18
19
    other_data = JSONField(null=True, default={})


Florent Chehab's avatar
Florent Chehab committed
20
21
22
23
24
25
26
class UserDataSerializer(MyModelSerializer):
    owner = serializers.CharField(read_only=True)

    def my_pre_save(self):
        user = self.get_user_in_request()
        self.override_validated_data({'owner': user})

27
28
29
30
31
        # we try to recover the correct instance
        query = UserData.objects.filter(owner=user)
        if len(query) == 1:
            self.instance = query[0]

32
33
34
    class Meta:
        model = UserData
        fields = '__all__'
Florent Chehab's avatar
Florent Chehab committed
35
        NEVER_MODERATE = True
36
37


Florent Chehab's avatar
Florent Chehab committed
38
39
40
41
42
43
class UserDataViewSet(MyModelViewSet):
    permission_classes = (
        permissions.IsAuthenticated,
        NoDelete,
        IsOwner
    )
44
    serializer_class = UserDataSerializer
Florent Chehab's avatar
Florent Chehab committed
45
46
47

    def get_queryset(self):
        return UserData.objects.filter(owner=self.request.user)  # pylint: disable=E1101