ad716a3cc12d94502986afd95e5961557e70e4da
[wolnelektury.git] / src / social / forms.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 import forms
5
6 from catalogue.models import Book, Tag
7 from social.utils import get_set
8
9
10 class UserSetsForm(forms.Form):
11     def __init__(self, book, user, *args, **kwargs):
12         super(UserSetsForm, self).__init__(*args, **kwargs)
13         self.fields['set_ids'] = forms.ChoiceField(
14             choices=[(tag.id, tag.name) for tag in Tag.objects.filter(category='set', user=user).iterator()],
15         )
16
17
18 class AddSetForm(forms.Form):
19     name = forms.CharField(max_length=50)
20     book = forms.IntegerField()
21
22     def save(self, user):
23         name = self.cleaned_data['name'].strip()
24         if not name: return
25         tag = get_set(user, name)
26         try:
27             book = Book.objects.get(id=self.cleaned_data['book'])
28         except Book.DoesNotExist:
29             return
30
31         try:
32             book.tag_relations.create(tag=tag)
33         except:
34             pass
35
36         return book, tag
37
38
39 class RemoveSetForm(forms.Form):
40     slug = forms.CharField(max_length=50)
41     book = forms.IntegerField()
42
43     def save(self, user):
44         slug = self.cleaned_data['slug']
45         try:
46             tag = Tag.objects.get(user=user, slug=slug)
47         except Tag.DoesNotExist:
48             return
49         try:
50             book = Book.objects.get(id=self.cleaned_data['book'])
51         except Book.DoesNotExist:
52             return
53
54         try:
55             book.tag_relations.filter(tag=tag).delete()
56         except:
57             pass
58
59         return book, tag