publish log + some fixes
[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 django.contrib.auth.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
13
14 class DocumentCreateForm(forms.ModelForm):
15     """
16         Form used for creating new documents.
17     """
18     file = forms.FileField(required=False)
19     text = forms.CharField(required=False, widget=forms.Textarea)
20
21     class Meta:
22         model = Book
23         exclude = ['gallery', 'parent', 'parent_number']
24         prepopulated_fields = {'slug': ['title']}
25
26     def clean(self):
27         super(DocumentCreateForm, self).clean()
28         file = self.cleaned_data['file']
29
30         if file is not None:
31             try:
32                 self.cleaned_data['text'] = file.read().decode('utf-8')
33             except UnicodeDecodeError:
34                 raise forms.ValidationError("Text file must be UTF-8 encoded.")
35
36         if not self.cleaned_data["text"]:
37             raise forms.ValidationError("You must either enter text or upload a file")
38
39         return self.cleaned_data
40
41
42 class DocumentsUploadForm(forms.Form):
43     """
44         Form used for uploading new documents.
45     """
46     file = forms.FileField(required=True, label=_('ZIP file'))
47
48     def clean(self):
49         file = self.cleaned_data['file']
50
51         import zipfile
52         try:
53             z = self.cleaned_data['zip'] = zipfile.ZipFile(file)
54         except zipfile.BadZipfile:
55             raise forms.ValidationError("Should be a ZIP file.")
56         if z.testzip():
57             raise forms.ValidationError("ZIP file corrupt.")
58
59         return self.cleaned_data
60
61
62 class ChunkForm(forms.ModelForm):
63     """
64         Form used for editing a chunk.
65     """
66     user = forms.ModelChoiceField(queryset=
67         User.objects.annotate(count=Count('chunk')).
68         order_by('-count', 'last_name', 'first_name'), required=False)
69
70
71     class Meta:
72         model = Chunk
73         exclude = ['number']
74
75     def clean_slug(self):
76         slug = self.cleaned_data['slug']
77         try:
78             chunk = Chunk.objects.get(book=self.instance.book, slug=slug)
79         except Chunk.DoesNotExist:
80             return slug
81         if chunk == self.instance:
82             return slug
83         raise forms.ValidationError(_('Chunk with this slug already exists'))
84
85
86 class ChunkAddForm(ChunkForm):
87     """
88         Form used for adding a chunk to a document.
89     """
90
91     def clean_slug(self):
92         slug = self.cleaned_data['slug']
93         try:
94             user = Chunk.objects.get(book=self.instance.book, slug=slug)
95         except Chunk.DoesNotExist:
96             return slug
97         raise forms.ValidationError(_('Chunk with this slug already exists'))
98
99
100 class BookAppendForm(forms.Form):
101     """
102         Form for appending a book to another book.
103         It means moving all chunks from book A to book B and deleting A.
104     """
105
106     append_to = forms.ModelChoiceField(queryset=Book.objects.all(),
107         label=_("Append to"))
108
109
110 class BookForm(forms.ModelForm):
111     """
112         Form used for editing a Book.
113     """
114
115     class Meta:
116         model = Book
117
118
119 class ChooseMasterForm(forms.Form):
120     """
121         Form used for fixing the chunks in a book.
122     """
123
124     master = forms.ChoiceField(choices=((m, m) for m in MASTERS))