1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from django import forms
5 from django.utils.translation import gettext_lazy as _
7 from catalogue.models import Book, Tag
8 from catalogue import utils
9 from social.utils import get_set, set_sets
12 class UserSetsForm(forms.Form):
13 def __init__(self, book, user, *args, **kwargs):
14 super(UserSetsForm, self).__init__(*args, **kwargs)
15 self.fields['set_ids'] = forms.ChoiceField(
16 choices=[(tag.id, tag.name) for tag in Tag.objects.filter(category='set', user=user).iterator()],
20 class ObjectSetsForm(forms.Form):
21 tags = forms.CharField(label=_('Tags (comma-separated)'), required=False,
22 widget=forms.Textarea())
24 def __init__(self, obj, user, *args, **kwargs):
27 data = kwargs.setdefault('data', {})
28 if 'tags' not in data and user.is_authenticated:
29 data['tags'] = ', '.join(
30 obj.tags.filter(category='set', user=user).exclude(name__in=(None, '')).values_list('name', flat=True))
31 super(ObjectSetsForm, self).__init__(*args, **kwargs)
33 def save(self, request):
34 tags = [get_set(self._user, tag_name.strip()) for tag_name in self.cleaned_data['tags'].split(',')]
35 set_sets(self._user, self._obj, tags)
39 class NewSetForm(forms.Form):
40 name = forms.CharField(max_length=50, required=True)
42 def __init__(self, *args, **kwargs):
43 super(NewSetForm, self).__init__(*args, **kwargs)
44 self.fields['name'].widget.attrs['title'] = _('Name of the new shelf')
46 def save(self, user, commit=True):
47 name = self.cleaned_data['name']
48 new_set = Tag(name=name, slug=utils.get_random_hash(name), sort_key=name.lower(), category='set', user=user)
54 class AddSetForm(forms.Form):
55 name = forms.CharField(max_length=50)
56 book = forms.IntegerField()
59 name = self.cleaned_data['name'].strip()
61 tag = get_set(user, name)
63 book = Book.objects.get(id=self.cleaned_data['book'])
64 except Book.DoesNotExist:
68 book.tag_relations.create(tag=tag)
75 class RemoveSetForm(forms.Form):
76 slug = forms.CharField(max_length=50)
77 book = forms.IntegerField()
80 slug = self.cleaned_data['slug']
82 tag = Tag.objects.get(user=user, slug=slug)
83 except Tag.DoesNotExist:
86 book = Book.objects.get(id=self.cleaned_data['book'])
87 except Book.DoesNotExist:
91 book.tag_relations.filter(tag=tag).delete()