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