viewsets.py 1.94 KB
Newer Older
1
from django.utils.translation import get_language_from_request
2
from rest_framework import permissions
3
4
from rest_framework.decorators import list_route
from rest_framework.response import Response
5
6
7
from rest_framework.viewsets import ModelViewSet

from pushnotifications.api.permissions import IsOwner
8
9
from pushnotifications.api.serializers import (DeviceSerializer,
                                               CategorySerializer)
10
from pushnotifications.models import Device, Category
11
12
13
14
15
16
17
18
19
20
21
22


class DeviceViewSet(ModelViewSet):
    permission_classes = (permissions.IsAuthenticated, IsOwner)
    queryset = Device.objects.all()
    serializer_class = DeviceSerializer

    def get_queryset(self):
        # filter all devices to only those belonging to the current user
        return self.queryset.filter(user=self.request.user)

    def perform_create(self, serializer):
23
        language = get_language_from_request(self.request)
24

25
26
27
28
29
30
31
        try:
            serializer.instance = Device.objects.get(
                user=self.request.user,
                registration_id=serializer.validated_data['registration_id']
            )
        except Device.DoesNotExist:
            pass
32
33
        data = serializer.validated_data
        if 'receive_category' in data and len(data['receive_category']) > 0:
34
35
36
            categories = data['receive_catogory'] + ['general']
            serializer.save(user=self.request.user, language=language,
                            receive_category=categories)
37
38
39
40
        else:
            categories = [c.pk for c in Category.objects.all()]
            serializer.save(user=self.request.user, language=language,
                            receive_category=categories)
41
42
43

    def perform_update(self, serializer):
        serializer.save(user=self.request.user)
44
45
46
47
48
49

    @list_route()
    def categories(self, request):
        categories = Category.objects.all()
        serializer = CategorySerializer(categories, many=True)
        return Response(serializer.data)