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