More API views migrated.
[wolnelektury.git] / src / api / views.py
1 from django.http import Http404
2 from rest_framework.permissions import IsAuthenticated
3 from rest_framework.response import Response
4 from rest_framework.views import APIView
5 from rest_framework.generics import RetrieveAPIView, get_object_or_404
6 from catalogue.models import Book
7 from .models import BookUserData
8 from . import serializers
9
10
11 class UserView(RetrieveAPIView):
12     permission_classes = [IsAuthenticated]
13     serializer_class = serializers.UserSerializer
14
15     def get_object(self):
16         return self.request.user
17
18
19 class BookUserDataView(RetrieveAPIView):
20     permission_classes = [IsAuthenticated]
21     serializer_class = serializers.BookUserDataSerializer
22     lookup_field = 'book__slug'
23     lookup_url_kwarg = 'slug'
24
25     def get_queryset(self):
26         return BookUserData.objects.filter(user=self.request.user)
27
28     def get(self, *args, **kwargs):
29         try:
30             return super(BookUserDataView, self).get(*args, **kwargs)
31         except Http404:
32             return Response({"state": "not_started"})
33
34     def post(self, request, slug, state):
35         if state not in ('reading', 'complete'):
36             raise Http404
37
38         book = get_object_or_404(Book, slug=slug)
39         instance = BookUserData.update(book, request.user, state)
40         serializer = self.get_serializer(instance)
41         return Response(serializer.data)