#1769: joining a document's history
[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 = ['parent', 'parent_number']
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['gallery'].widget.attrs={'class': 'autoslug'}
29         self.fields['title'].widget.attrs={'class': 'autoslug-source'}
30
31     def clean(self):
32         super(DocumentCreateForm, self).clean()
33         file = self.cleaned_data['file']
34
35         if file is not None:
36             try:
37                 self.cleaned_data['text'] = file.read().decode('utf-8')
38             except UnicodeDecodeError:
39                 raise forms.ValidationError(_("Text file must be UTF-8 encoded."))
40
41         if not self.cleaned_data["text"]:
42             self._errors["file"] = self.error_class([_("You must either enter text or upload a file")])
43
44         return self.cleaned_data
45
46
47 class DocumentsUploadForm(forms.Form):
48     """
49         Form used for uploading new documents.
50     """
51     file = forms.FileField(required=True, label=_('ZIP file'))
52     dirs = forms.BooleanField(label=_('Directories are documents in chunks'),
53             widget = forms.CheckboxInput(attrs={'disabled':'disabled'}))
54
55     def clean(self):
56         file = self.cleaned_data['file']
57
58         import zipfile
59         try:
60             z = self.cleaned_data['zip'] = zipfile.ZipFile(file)
61         except zipfile.BadZipfile:
62             raise forms.ValidationError("Should be a ZIP file.")
63         if z.testzip():
64             raise forms.ValidationError("ZIP file corrupt.")
65
66         return self.cleaned_data
67
68
69 class ChunkForm(forms.ModelForm):
70     """
71         Form used for editing a chunk.
72     """
73     user = forms.ModelChoiceField(queryset=
74         User.objects.annotate(count=Count('chunk')).
75         order_by('-count', 'last_name', 'first_name'), required=False,
76         label=_('Assigned to')) 
77
78     class Meta:
79         model = Chunk
80         fields = ['title', 'slug', 'user', 'stage']
81         exclude = ['number']
82
83     def __init__(self, *args, **kwargs):
84         super(ChunkForm, self).__init__(*args, **kwargs)
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(),
119             label=_("Append to"))
120
121     def __init__(self, book, *args, **kwargs):
122         ret =  super(BookAppendForm, self).__init__(*args, **kwargs)
123         self.fields['append_to'].queryset = Book.objects.exclude(pk=book.pk)
124         return ret
125
126
127 class BookForm(forms.ModelForm):
128     """Form used for editing a Book."""
129
130     class Meta:
131         model = Book
132
133     def __init__(self, *args, **kwargs):
134         ret = super(BookForm, self).__init__(*args, **kwargs)
135         self.fields['slug'].widget.attrs.update({"class": "autoslug"})
136         self.fields['title'].widget.attrs.update({"class": "autoslug-source"})
137         return ret
138
139
140 class ReadonlyBookForm(BookForm):
141     """Form used for not editing a Book."""
142
143     def __init__(self, *args, **kwargs):
144         ret = super(ReadonlyBookForm, self).__init__(*args, **kwargs)
145         for field in self.fields.values():
146             field.widget.attrs.update({"readonly": True})
147         return ret
148
149
150 class ChooseMasterForm(forms.Form):
151     """
152         Form used for fixing the chunks in a book.
153     """
154
155     master = forms.ChoiceField(choices=((m, m) for m in MASTERS))