Editor update - trimming down toolbar
[redakcja.git] / apps / catalogue / forms.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 from catalogue.models import User
7 from django.db.models import Count
8 from django import forms
9 from django.utils.translation import ugettext_lazy as _
10
11 from catalogue.constants import MASTERS
12 from catalogue.models import Book, Chunk, Template
13
14 class DocumentCreateForm(forms.ModelForm):
15     """
16         Form used for creating new documents.
17     """
18     file = forms.FileField(required=False)
19     template = forms.ModelChoiceField(Template.objects, required=False)
20     text = forms.CharField(required=False, widget=forms.Textarea)
21
22     class Meta:
23         model = Book
24         exclude = ['parent', 'parent_number', 'project']
25
26     def __init__(self, *args, **kwargs):
27         super(DocumentCreateForm, self).__init__(*args, **kwargs)
28         self.fields['slug'].widget.attrs={'class': 'autoslug'}
29         self.fields['gallery'].widget.attrs={'class': 'autoslug'}
30         self.fields['title'].widget.attrs={'class': 'autoslug-source'}
31         self.fields['template'].queryset = Template.objects.filter(is_main=True)
32
33     def clean(self):
34         super(DocumentCreateForm, self).clean()
35         file = self.cleaned_data['file']
36         template = self.cleaned_data['template']
37
38         if file is not None:
39             try:
40                 self.cleaned_data['text'] = file.read().decode('utf-8')
41             except UnicodeDecodeError:
42                 raise forms.ValidationError(_("Text file must be UTF-8 encoded."))
43         elif template is not None:
44             self.cleaned_data['text'] = template.content
45
46         if not self.cleaned_data["text"]:
47             self._errors["file"] = self.error_class([_("You must enter text, upload a file or select a template")])
48
49         return self.cleaned_data
50
51
52 class DocumentsUploadForm(forms.Form):
53     """
54         Form used for uploading new documents.
55     """
56     file = forms.FileField(required=True, label=_('ZIP file'))
57     dirs = forms.BooleanField(label=_('Directories are documents in chunks'),
58             widget = forms.CheckboxInput(attrs={'disabled':'disabled'}))
59
60     def clean(self):
61         file = self.cleaned_data['file']
62
63         import zipfile
64         try:
65             z = self.cleaned_data['zip'] = zipfile.ZipFile(file)
66         except zipfile.BadZipfile:
67             raise forms.ValidationError("Should be a ZIP file.")
68         if z.testzip():
69             raise forms.ValidationError("ZIP file corrupt.")
70
71         return self.cleaned_data
72
73
74 class ChunkForm(forms.ModelForm):
75     """
76         Form used for editing a chunk.
77     """
78     user = forms.ModelChoiceField(queryset=
79         User.objects.annotate(count=Count('chunk')).
80         order_by('last_name', 'first_name'), required=False,
81         label=_('Assigned to')) 
82
83     class Meta:
84         model = Chunk
85         fields = ['title', 'slug', 'gallery_start', 'user', 'stage']
86         exclude = ['number']
87
88     def __init__(self, *args, **kwargs):
89         super(ChunkForm, self).__init__(*args, **kwargs)
90         self.fields['gallery_start'].widget.attrs={'class': 'number-input'}
91         self.fields['slug'].widget.attrs={'class': 'autoslug'}
92         self.fields['title'].widget.attrs={'class': 'autoslug-source'}
93
94     def clean_slug(self):
95         slug = self.cleaned_data['slug']
96         try:
97             chunk = Chunk.objects.get(book=self.instance.book, slug=slug)
98         except Chunk.DoesNotExist:
99             return slug
100         if chunk == self.instance:
101             return slug
102         raise forms.ValidationError(_('Chunk with this slug already exists'))
103
104
105 class ChunkAddForm(ChunkForm):
106     """
107         Form used for adding a chunk to a document.
108     """
109
110     def clean_slug(self):
111         slug = self.cleaned_data['slug']
112         try:
113             user = Chunk.objects.get(book=self.instance.book, slug=slug)
114         except Chunk.DoesNotExist:
115             return slug
116         raise forms.ValidationError(_('Chunk with this slug already exists'))
117
118
119 class BookAppendForm(forms.Form):
120     """
121         Form for appending a book to another book.
122         It means moving all chunks from book A to book B and deleting A.
123     """
124     append_to = forms.ModelChoiceField(queryset=Book.objects.all(),
125             label=_("Append to"))
126
127     def __init__(self, book, *args, **kwargs):
128         ret =  super(BookAppendForm, self).__init__(*args, **kwargs)
129         self.fields['append_to'].queryset = Book.objects.exclude(pk=book.pk)
130         return ret
131
132
133 class BookForm(forms.ModelForm):
134     """Form used for editing a Book."""
135
136     class Meta:
137         model = Book
138         exclude = ['project']
139
140     def __init__(self, *args, **kwargs):
141         ret = super(BookForm, self).__init__(*args, **kwargs)
142         self.fields['slug'].widget.attrs.update({"class": "autoslug"})
143         self.fields['title'].widget.attrs.update({"class": "autoslug-source"})
144         return ret
145
146
147 class ReadonlyBookForm(BookForm):
148     """Form used for not editing a Book."""
149
150     def __init__(self, *args, **kwargs):
151         ret = super(ReadonlyBookForm, self).__init__(*args, **kwargs)
152         for field in self.fields.values():
153             field.widget.attrs.update({"readonly": True})
154         return ret
155
156
157 class ChooseMasterForm(forms.Form):
158     """
159         Form used for fixing the chunks in a book.
160     """
161
162     master = forms.ChoiceField(choices=((m, m) for m in MASTERS))