89661590e82795f570c0256924d3006ee879936f
[wolnelektury.git] / src / social / views.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
3 #
4 from django.shortcuts import render, get_object_or_404, redirect
5 from django.http import HttpResponseForbidden, JsonResponse
6 from django.contrib.auth.decorators import login_required
7 from django.views.decorators.http import require_POST
8
9 from ajaxable.utils import AjaxableFormView
10
11 from catalogue.models import Book
12 from social import forms
13 from wolnelektury.utils import is_ajax
14
15
16 # ====================
17 # = Shelf management =
18 # ====================
19
20
21 @require_POST
22 def like_book(request, slug):
23     if not request.user.is_authenticated:
24         return HttpResponseForbidden('Login required.')
25     book = get_object_or_404(Book, slug=slug)
26
27     book.like(request.user)
28
29     if is_ajax(request):
30         return JsonResponse({"success": True, "msg": "ok", "like": True})
31     else:
32         return redirect(book)
33
34
35 @require_POST
36 def unlike_book(request, slug):
37     if not request.user.is_authenticated:
38         return HttpResponseForbidden('Login required.')
39     book = get_object_or_404(Book, slug=slug)
40
41     book.unlike(request.user)
42
43     if is_ajax(request):
44         return JsonResponse({"success": True, "msg": "ok", "like": False})
45     else:
46         return redirect(book)
47
48
49 @login_required
50 def my_shelf(request):
51     return render(request, 'social/my_shelf.html', {
52         'books': Book.tagged.with_any(request.user.tag_set.all())
53     })
54
55
56 class ObjectSetsFormView(AjaxableFormView):
57     form_class = forms.ObjectSetsForm
58     placeholdize = True
59     template = 'social/sets_form.html'
60     ajax_redirect = True
61     POST_login = True
62
63     def get_object(self, request, slug):
64         return get_object_or_404(Book, slug=slug)
65
66     def context_description(self, request, obj):
67         return obj.pretty_title()
68
69     def form_args(self, request, obj):
70         return (obj, request.user), {}