688e5edd0b42580243f4cd77674ca84f9192e414
[wolnelektury.git] / apps / catalogue / forms.py
1 # -*- coding: utf-8 -*-
2 from django import forms
3 from slughifi import slughifi
4
5 from catalogue.models import Tag
6 from catalogue.fields import JQueryAutoCompleteField
7 from catalogue import utils
8
9
10 class SearchForm(forms.Form):
11     q = JQueryAutoCompleteField('/katalog/tags/', {'minChars': 2, 'selectFirst': True, 'cacheLength': 50})
12     tags = forms.CharField(widget=forms.HiddenInput, required=False)
13     
14     def __init__(self, *args, **kwargs):
15         tags = kwargs.pop('tags', [])
16         super(SearchForm, self).__init__(*args, **kwargs)
17         self.fields['q'].widget.attrs['title'] = u'tytuł, autor, motyw, epoka, rodzaj, gatunek literacki'
18         self.fields['tags'].initial = '/'.join(tag.slug for tag in Tag.get_tag_list(tags))
19
20
21 class UserSetsForm(forms.Form):
22     def __init__(self, book, user, *args, **kwargs):
23         super(UserSetsForm, self).__init__(*args, **kwargs)
24         self.fields['set_ids'] = forms.ChoiceField(
25             choices=[(tag.id, tag.name) for tag in Tag.objects.filter(category='set', user=user)],
26         )
27
28
29 class ObjectSetsForm(forms.Form):
30     def __init__(self, obj, user, *args, **kwargs):        
31         super(ObjectSetsForm, self).__init__(*args, **kwargs)
32         self.fields['set_ids'] = forms.MultipleChoiceField(
33             label=u'Półki',
34             required=False,
35             choices=[(tag.id, tag.name) for tag in Tag.objects.filter(category='set', user=user)],
36             initial=[tag.id for tag in obj.tags.filter(category='set', user=user)],
37             widget=forms.CheckboxSelectMultiple
38         )
39         
40
41 class NewSetForm(forms.Form):
42     name = forms.CharField(max_length=50, required=True)
43     
44     def __init__(self, *args, **kwargs):
45         super(NewSetForm, self).__init__(*args, **kwargs)
46         self.fields['name'].widget.attrs['title'] = u'nazwa nowej półki'
47         
48     def save(self, user, commit=True):
49         name = self.cleaned_data['name']
50         new_set = Tag(name=name, slug=utils.get_random_hash(name), sort_key=slughifi(name),
51             category='set', user=user)
52         
53         new_set.save()
54         return new_set
55