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 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 _
11 from catalogue.constants import MASTERS
12 from catalogue.models import Book, Chunk, Template
14 class DocumentCreateForm(forms.ModelForm):
16 Form used for creating new documents.
18 file = forms.FileField(required=False)
19 template = forms.ModelChoiceField(Template.objects, required=False)
20 text = forms.CharField(required=False, widget=forms.Textarea)
24 exclude = ['parent', 'parent_number', 'project']
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 self.fields['template'].queryset = Template.objects.filter(is_main=True)
34 super(DocumentCreateForm, self).clean()
35 file = self.cleaned_data['file']
36 template = self.cleaned_data['template']
40 self.cleaned_data['text'] = file.read().decode('utf-8')
41 except UnicodeDecodeError:
42 raise forms.ValidationError(_("Text file must be UTF-8 encoded."))
43 elif template is not None:
44 self.cleaned_data['text'] = template.content
46 if not self.cleaned_data["text"]:
47 self._errors["file"] = self.error_class([_("You must enter text, upload a file or select a template")])
49 return self.cleaned_data
52 class DocumentsUploadForm(forms.Form):
54 Form used for uploading new documents.
56 file = forms.FileField(required=True, label=_('ZIP file'))
57 dirs = forms.BooleanField(label=_('Directories are documents in chunks'),
58 widget = forms.CheckboxInput(attrs={'disabled':'disabled'}))
61 file = self.cleaned_data['file']
65 z = self.cleaned_data['zip'] = zipfile.ZipFile(file)
66 except zipfile.BadZipfile:
67 raise forms.ValidationError("Should be a ZIP file.")
69 raise forms.ValidationError("ZIP file corrupt.")
71 return self.cleaned_data
74 class ChunkForm(forms.ModelForm):
76 Form used for editing a chunk.
78 user = forms.ModelChoiceField(queryset=
79 User.objects.annotate(count=Count('chunk')).
80 order_by('last_name', 'first_name'), required=False,
81 label=_('Assigned to'))
85 fields = ['title', 'slug', 'gallery_start', 'user', 'stage']
88 def __init__(self, *args, **kwargs):
89 super(ChunkForm, self).__init__(*args, **kwargs)
90 self.fields['gallery_start'].widget.attrs={'class': 'number-input'}
91 self.fields['slug'].widget.attrs={'class': 'autoslug'}
92 self.fields['title'].widget.attrs={'class': 'autoslug-source'}
95 slug = self.cleaned_data['slug']
97 chunk = Chunk.objects.get(book=self.instance.book, slug=slug)
98 except Chunk.DoesNotExist:
100 if chunk == self.instance:
102 raise forms.ValidationError(_('Chunk with this slug already exists'))
105 class ChunkAddForm(ChunkForm):
107 Form used for adding a chunk to a document.
110 def clean_slug(self):
111 slug = self.cleaned_data['slug']
113 user = Chunk.objects.get(book=self.instance.book, slug=slug)
114 except Chunk.DoesNotExist:
116 raise forms.ValidationError(_('Chunk with this slug already exists'))
119 class BookAppendForm(forms.Form):
121 Form for appending a book to another book.
122 It means moving all chunks from book A to book B and deleting A.
124 append_to = forms.ModelChoiceField(queryset=Book.objects.all(),
125 label=_("Append to"))
127 def __init__(self, book, *args, **kwargs):
128 ret = super(BookAppendForm, self).__init__(*args, **kwargs)
129 self.fields['append_to'].queryset = Book.objects.exclude(pk=book.pk)
133 class BookForm(forms.ModelForm):
134 """Form used for editing a Book."""
138 exclude = ['project']
140 def __init__(self, *args, **kwargs):
141 ret = super(BookForm, self).__init__(*args, **kwargs)
142 self.fields['slug'].widget.attrs.update({"class": "autoslug"})
143 self.fields['title'].widget.attrs.update({"class": "autoslug-source"})
147 class ReadonlyBookForm(BookForm):
148 """Form used for not editing a Book."""
150 def __init__(self, *args, **kwargs):
151 ret = super(ReadonlyBookForm, self).__init__(*args, **kwargs)
152 for field in self.fields.values():
153 field.widget.attrs.update({"readonly": True})
157 class ChooseMasterForm(forms.Form):
159 Form used for fixing the chunks in a book.
162 master = forms.ChoiceField(choices=((m, m) for m in MASTERS))