l10n fix
[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     dirs = forms.BooleanField(label=_('Directories are documents in chunks'),
48             widget = forms.CheckboxInput(attrs={'disabled':'disabled'}))
49
50     def clean(self):
51         file = self.cleaned_data['file']
52
53         import zipfile
54         try:
55             z = self.cleaned_data['zip'] = zipfile.ZipFile(file)
56         except zipfile.BadZipfile:
57             raise forms.ValidationError("Should be a ZIP file.")
58         if z.testzip():
59             raise forms.ValidationError("ZIP file corrupt.")
60
61         return self.cleaned_data
62
63
64 class ChunkForm(forms.ModelForm):
65     """
66         Form used for editing a chunk.
67     """
68     user = forms.ModelChoiceField(queryset=
69         User.objects.annotate(count=Count('chunk')).
70         order_by('-count', 'last_name', 'first_name'), required=False,
71         label=_('Assigned to')) 
72
73     class Meta:
74         model = Chunk
75         fields = ['title', 'slug', 'user', 'stage']
76         exclude = ['number']
77
78     def __init__(self, *args, **kwargs):
79         super(ChunkForm, self).__init__(*args, **kwargs)
80         self.fields['slug'].widget.attrs={'class': 'autoslug'}
81         self.fields['title'].widget.attrs={'class': 'autoslug-source'}
82
83     def clean_slug(self):
84         slug = self.cleaned_data['slug']
85         try:
86             chunk = Chunk.objects.get(book=self.instance.book, slug=slug)
87         except Chunk.DoesNotExist:
88             return slug
89         if chunk == self.instance:
90             return slug
91         raise forms.ValidationError(_('Chunk with this slug already exists'))
92
93
94 class ChunkAddForm(ChunkForm):
95     """
96         Form used for adding a chunk to a document.
97     """
98
99     def clean_slug(self):
100         slug = self.cleaned_data['slug']
101         try:
102             user = Chunk.objects.get(book=self.instance.book, slug=slug)
103         except Chunk.DoesNotExist:
104             return slug
105         raise forms.ValidationError(_('Chunk with this slug already exists'))
106
107
108 class BookAppendForm(forms.Form):
109     """
110         Form for appending a book to another book.
111         It means moving all chunks from book A to book B and deleting A.
112     """
113     append_to = forms.ModelChoiceField(queryset=Book.objects.all(),
114             label=_("Append to"))
115
116     def __init__(self, book, *args, **kwargs):
117         ret =  super(BookAppendForm, self).__init__(*args, **kwargs)
118         self.fields['append_to'].queryset = Book.objects.exclude(pk=book.pk)
119         return ret
120
121
122 class BookForm(forms.ModelForm):
123     """Form used for editing a Book."""
124
125     class Meta:
126         model = Book
127
128     def __init__(self, *args, **kwargs):
129         ret = super(BookForm, self).__init__(*args, **kwargs)
130         self.fields['slug'].widget.attrs.update({"class": "autoslug"})
131         self.fields['title'].widget.attrs.update({"class": "autoslug-source"})
132         return ret
133
134
135 class ReadonlyBookForm(BookForm):
136     """Form used for not editing a Book."""
137
138     def __init__(self, *args, **kwargs):
139         ret = super(ReadonlyBookForm, self).__init__(*args, **kwargs)
140         for field in self.fields.values():
141             field.widget.attrs.update({"readonly": True})
142         return ret
143
144
145 class ChooseMasterForm(forms.Form):
146     """
147         Form used for fixing the chunks in a book.
148     """
149
150     master = forms.ChoiceField(choices=((m, m) for m in MASTERS))