5834ffa245be0f1ef53ede19bb7a128ac309eeed
[wolnelektury.git] / apps / social / forms.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 import forms
6 from django.utils.translation import ugettext_lazy as _
7
8 from catalogue.models import Tag
9 from catalogue import utils
10 from social.utils import get_set, set_sets
11
12
13 class UserSetsForm(forms.Form):
14     def __init__(self, book, user, *args, **kwargs):
15         super(UserSetsForm, self).__init__(*args, **kwargs)
16         self.fields['set_ids'] = forms.ChoiceField(
17             choices=[(tag.id, tag.name) for tag in
18                 Tag.objects.filter(category='set', user=user).iterator()],
19         )
20
21
22 class ObjectSetsForm(forms.Form):
23     tags = forms.CharField(label=_('Tags (comma-separated)'), required=False,
24                            widget=forms.Textarea())
25
26     def __init__(self, obj, user, *args, **kwargs):
27         self._obj = obj
28         self._user = user
29         data = kwargs.setdefault('data', {})
30         if 'tags' not in data and user.is_authenticated():
31             data['tags'] = ', '.join(t.name
32                 for t in obj.tags.filter(category='set', user=user).iterator() if t.name)
33         super(ObjectSetsForm, self).__init__(*args, **kwargs)
34
35     def save(self, request):
36         tags = [get_set(self._user, tag_name.strip())
37                     for tag_name in self.cleaned_data['tags'].split(',')]
38         set_sets(self._user, self._obj, tags)
39         return {"like": True}
40
41
42 class NewSetForm(forms.Form):
43     name = forms.CharField(max_length=50, required=True)
44
45     def __init__(self, *args, **kwargs):
46         super(NewSetForm, self).__init__(*args, **kwargs)
47         self.fields['name'].widget.attrs['title'] = _('Name of the new shelf')
48
49     def save(self, user, commit=True):
50         name = self.cleaned_data['name']
51         new_set = Tag(name=name, slug=utils.get_random_hash(name), sort_key=name.lower(),
52             category='set', user=user)
53
54         new_set.save()
55         return new_set