1 # -*- coding: utf-8 -*-
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.
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 _
11 from catalogue.constants import MASTERS
12 from catalogue.models import Book, Chunk
14 class DocumentCreateForm(forms.ModelForm):
16 Form used for creating new documents.
18 file = forms.FileField(required=False)
19 text = forms.CharField(required=False, widget=forms.Textarea)
23 exclude = ['gallery', 'parent', 'parent_number']
24 prepopulated_fields = {'slug': ['title']}
27 super(DocumentCreateForm, self).clean()
28 file = self.cleaned_data['file']
32 self.cleaned_data['text'] = file.read().decode('utf-8')
33 except UnicodeDecodeError:
34 raise forms.ValidationError("Text file must be UTF-8 encoded.")
36 if not self.cleaned_data["text"]:
37 raise forms.ValidationError("You must either enter text or upload a file")
39 return self.cleaned_data
42 class DocumentsUploadForm(forms.Form):
44 Form used for uploading new documents.
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'}))
51 file = self.cleaned_data['file']
55 z = self.cleaned_data['zip'] = zipfile.ZipFile(file)
56 except zipfile.BadZipfile:
57 raise forms.ValidationError("Should be a ZIP file.")
59 raise forms.ValidationError("ZIP file corrupt.")
61 return self.cleaned_data
64 class ChunkForm(forms.ModelForm):
66 Form used for editing a chunk.
68 user = forms.ModelChoiceField(queryset=
69 User.objects.annotate(count=Count('chunk')).
70 order_by('-count', 'last_name', 'first_name'), required=False)
78 slug = self.cleaned_data['slug']
80 chunk = Chunk.objects.get(book=self.instance.book, slug=slug)
81 except Chunk.DoesNotExist:
83 if chunk == self.instance:
85 raise forms.ValidationError(_('Chunk with this slug already exists'))
88 class ChunkAddForm(ChunkForm):
90 Form used for adding a chunk to a document.
94 slug = self.cleaned_data['slug']
96 user = Chunk.objects.get(book=self.instance.book, slug=slug)
97 except Chunk.DoesNotExist:
99 raise forms.ValidationError(_('Chunk with this slug already exists'))
102 class BookAppendForm(forms.Form):
104 Form for appending a book to another book.
105 It means moving all chunks from book A to book B and deleting A.
108 append_to = forms.ModelChoiceField(queryset=Book.objects.all(),
109 label=_("Append to"))
112 class BookForm(forms.ModelForm):
114 Form used for editing a Book.
121 class ChooseMasterForm(forms.Form):
123 Form used for fixing the chunks in a book.
126 master = forms.ChoiceField(choices=((m, m) for m in MASTERS))