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'}
33 super(DocumentCreateForm, self).clean()
34 file = self.cleaned_data['file']
35 template = self.cleaned_data['template']
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
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")])
48 return self.cleaned_data
51 class DocumentsUploadForm(forms.Form):
53 Form used for uploading new documents.
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'}))
60 file = self.cleaned_data['file']
64 z = self.cleaned_data['zip'] = zipfile.ZipFile(file)
65 except zipfile.BadZipfile:
66 raise forms.ValidationError("Should be a ZIP file.")
68 raise forms.ValidationError("ZIP file corrupt.")
70 return self.cleaned_data
73 class ChunkForm(forms.ModelForm):
75 Form used for editing a chunk.
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'))
84 fields = ['title', 'slug', 'gallery_start', 'user', 'stage']
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'}
94 slug = self.cleaned_data['slug']
96 chunk = Chunk.objects.get(book=self.instance.book, slug=slug)
97 except Chunk.DoesNotExist:
99 if chunk == self.instance:
101 raise forms.ValidationError(_('Chunk with this slug already exists'))
104 class ChunkAddForm(ChunkForm):
106 Form used for adding a chunk to a document.
109 def clean_slug(self):
110 slug = self.cleaned_data['slug']
112 user = Chunk.objects.get(book=self.instance.book, slug=slug)
113 except Chunk.DoesNotExist:
115 raise forms.ValidationError(_('Chunk with this slug already exists'))
118 class BookAppendForm(forms.Form):
120 Form for appending a book to another book.
121 It means moving all chunks from book A to book B and deleting A.
123 append_to = forms.ModelChoiceField(queryset=Book.objects.all(),
124 label=_("Append to"))
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)
132 class BookForm(forms.ModelForm):
133 """Form used for editing a Book."""
137 exclude = ['project']
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"})
146 class ReadonlyBookForm(BookForm):
147 """Form used for not editing a Book."""
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})
156 class ChooseMasterForm(forms.Form):
158 Form used for fixing the chunks in a book.
161 master = forms.ChoiceField(choices=((m, m) for m in MASTERS))