style
[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
15 class DocumentCreateForm(forms.ModelForm):
16     """
17         Form used for creating new documents.
18     """
19     template = forms.ModelChoiceField(Template.objects, required=False)
20
21     class Meta:
22         model = Book
23         exclude = ['parent', 'parent_number', 'project', 'gallery', 'public']
24
25     def __init__(self, *args, **kwargs):
26         super(DocumentCreateForm, self).__init__(*args, **kwargs)
27         self.fields['slug'].widget.attrs = {'class': 'autoslug'}
28         self.fields['title'].widget.attrs = {'class': 'autoslug-source'}
29         self.fields['template'].queryset = Template.objects.filter(is_main=True)
30
31     def clean(self):
32         super(DocumentCreateForm, self).clean()
33         template = self.cleaned_data['template']
34         self.cleaned_data['gallery'] = self.cleaned_data['slug']
35
36         if template is not None:
37             self.cleaned_data['text'] = template.content
38
39         if not self.cleaned_data.get("text"):
40             self._errors["template"] = self.error_class([_("You must select a template")])
41
42         return self.cleaned_data
43
44
45 class DocumentsUploadForm(forms.Form):
46     """
47         Form used for uploading new documents.
48     """
49     file = forms.FileField(required=True, label=_('ZIP file'))
50     dirs = forms.BooleanField(
51         label=_('Directories are documents in chunks'),
52         widget=forms.CheckboxInput(attrs={'disabled': 'disabled'}))
53
54     def clean(self):
55         zip_file = self.cleaned_data['zip_file']
56
57         import zipfile
58         try:
59             z = self.cleaned_data['zip'] = zipfile.ZipFile(zip_file)
60         except zipfile.BadZipfile:
61             raise forms.ValidationError("Should be a ZIP file.")
62         if z.testzip():
63             raise forms.ValidationError("ZIP file corrupt.")
64
65         return self.cleaned_data
66
67
68 class ChunkForm(forms.ModelForm):
69     """
70         Form used for editing a chunk.
71     """
72     user = forms.ModelChoiceField(
73         queryset=User.objects.annotate(count=Count('chunk')).order_by('last_name', 'first_name'),
74         required=False,
75         label=_('Assigned to'))
76
77     class Meta:
78         model = Chunk
79         fields = ['title', 'slug', 'gallery_start', 'user', 'stage']
80         exclude = ['number']
81
82     def __init__(self, *args, **kwargs):
83         super(ChunkForm, self).__init__(*args, **kwargs)
84         self.fields['gallery_start'].widget.attrs = {'class': 'number-input'}
85         self.fields['slug'].widget.attrs = {'class': 'autoslug'}
86         self.fields['title'].widget.attrs = {'class': 'autoslug-source'}
87
88     def clean_slug(self):
89         slug = self.cleaned_data['slug']
90         try:
91             chunk = Chunk.objects.get(book=self.instance.book, slug=slug)
92         except Chunk.DoesNotExist:
93             return slug
94         if chunk == self.instance:
95             return slug
96         raise forms.ValidationError(_('Chunk with this slug already exists'))
97
98
99 class ChunkAddForm(ChunkForm):
100     """
101         Form used for adding a chunk to a document.
102     """
103
104     def clean_slug(self):
105         slug = self.cleaned_data['slug']
106         try:
107             user = Chunk.objects.get(book=self.instance.book, slug=slug)
108         except Chunk.DoesNotExist:
109             return slug
110         raise forms.ValidationError(_('Chunk with this slug already exists'))
111
112
113 class BookAppendForm(forms.Form):
114     """
115         Form for appending a book to another book.
116         It means moving all chunks from book A to book B and deleting A.
117     """
118     append_to = forms.ModelChoiceField(queryset=Book.objects.all(), label=_("Append to"))
119
120     def __init__(self, book, *args, **kwargs):
121         super(BookAppendForm, self).__init__(*args, **kwargs)
122         self.fields['append_to'].queryset = Book.objects.exclude(pk=book.pk)
123
124
125 class BookForm(forms.ModelForm):
126     """Form used for editing a Book."""
127
128     class Meta:
129         model = Book
130         exclude = ['project']
131
132     def __init__(self, *args, **kwargs):
133         super(BookForm, self).__init__(*args, **kwargs)
134         self.fields['slug'].widget.attrs.update({"class": "autoslug"})
135         self.fields['title'].widget.attrs.update({"class": "autoslug-source"})
136
137
138 class ReadonlyBookForm(BookForm):
139     """Form used for not editing a Book."""
140
141     def __init__(self, *args, **kwargs):
142         super(ReadonlyBookForm, self).__init__(*args, **kwargs)
143         for field in self.fields.values():
144             field.widget.attrs.update({"readonly": True})
145
146
147 class ChooseMasterForm(forms.Form):
148     """
149         Form used for fixing the chunks in a book.
150     """
151
152     master = forms.ChoiceField(choices=((m, m) for m in MASTERS))