1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from django.db.models import Count
5 from django import forms
6 from django.utils.translation import ugettext_lazy as _
7 from django.conf import settings
9 from .constants import MASTERS
10 from .models import Book, Chunk, Image, User
12 class DocumentCreateForm(forms.ModelForm):
14 Form used for creating new documents.
16 file = forms.FileField(required=False)
17 text = forms.CharField(required=False, widget=forms.Textarea)
21 exclude = ['parent', 'parent_number', 'project']
23 def __init__(self, *args, **kwargs):
24 super(DocumentCreateForm, self).__init__(*args, **kwargs)
25 self.fields['slug'].widget.attrs={'class': 'autoslug'}
26 self.fields['gallery'].widget.attrs={'class': 'autoslug'}
27 self.fields['title'].widget.attrs={'class': 'autoslug-source'}
30 super(DocumentCreateForm, self).clean()
31 file = self.cleaned_data['file']
35 self.cleaned_data['text'] = file.read().decode('utf-8')
36 except UnicodeDecodeError:
37 raise forms.ValidationError(_("Text file must be UTF-8 encoded."))
39 if not self.cleaned_data["text"]:
40 self._errors["file"] = self.error_class([_("You must either enter text or upload a file")])
42 return self.cleaned_data
45 class DocumentsUploadForm(forms.Form):
47 Form used for uploading new documents.
49 file = forms.FileField(required=True, label=_('ZIP file'))
50 dirs = forms.BooleanField(label=_('Directories are documents in chunks'),
51 widget = forms.CheckboxInput(attrs={'disabled':'disabled'}))
54 file = self.cleaned_data['file']
58 z = self.cleaned_data['zip'] = zipfile.ZipFile(file)
59 except zipfile.BadZipfile:
60 raise forms.ValidationError("Should be a ZIP file.")
62 raise forms.ValidationError("ZIP file corrupt.")
64 return self.cleaned_data
67 class ChunkForm(forms.ModelForm):
69 Form used for editing a chunk.
71 user = forms.ModelChoiceField(queryset=
72 User.objects.annotate(count=Count('chunk')).
73 order_by('last_name', 'first_name'), required=False,
74 label=_('Assigned to'))
78 fields = ['title', 'slug', 'gallery_start', 'user', 'stage']
81 def __init__(self, *args, **kwargs):
82 super(ChunkForm, self).__init__(*args, **kwargs)
83 self.fields['gallery_start'].widget.attrs={'class': 'number-input'}
84 self.fields['slug'].widget.attrs={'class': 'autoslug'}
85 self.fields['title'].widget.attrs={'class': 'autoslug-source'}
88 slug = self.cleaned_data['slug']
90 chunk = Chunk.objects.get(book=self.instance.book, slug=slug)
91 except Chunk.DoesNotExist:
93 if chunk == self.instance:
95 raise forms.ValidationError(_('Chunk with this slug already exists'))
98 class ChunkAddForm(ChunkForm):
100 Form used for adding a chunk to a document.
103 def clean_slug(self):
104 slug = self.cleaned_data['slug']
106 user = Chunk.objects.get(book=self.instance.book, slug=slug)
107 except Chunk.DoesNotExist:
109 raise forms.ValidationError(_('Chunk with this slug already exists'))
112 class BookAppendForm(forms.Form):
114 Form for appending a book to another book.
115 It means moving all chunks from book A to book B and deleting A.
117 append_to = forms.ModelChoiceField(queryset=Book.objects.all(),
118 label=_("Append to"))
120 def __init__(self, book, *args, **kwargs):
121 ret = super(BookAppendForm, self).__init__(*args, **kwargs)
122 self.fields['append_to'].queryset = Book.objects.exclude(pk=book.pk)
126 class BookForm(forms.ModelForm):
127 """Form used for editing a Book."""
131 exclude = ['project']
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"})
139 def save(self, **kwargs):
140 orig_instance = Book.objects.get(pk=self.instance.pk)
141 old_gallery = orig_instance.gallery
142 new_gallery = self.cleaned_data['gallery']
143 if new_gallery and old_gallery and new_gallery != old_gallery:
146 from django.conf import settings
147 shutil.move(orig_instance.gallery_path(),
148 os.path.join(settings.MEDIA_ROOT, settings.IMAGE_DIR, new_gallery))
149 super(BookForm, self).save(**kwargs)
152 class ReadonlyBookForm(BookForm):
153 """Form used for not editing a Book."""
155 def __init__(self, *args, **kwargs):
156 ret = super(ReadonlyBookForm, self).__init__(*args, **kwargs)
157 for field in self.fields.values():
158 field.widget.attrs.update({"disabled": "disabled"})
162 class ChooseMasterForm(forms.Form):
164 Form used for fixing the chunks in a book.
167 master = forms.ChoiceField(choices=((m, m) for m in MASTERS))
170 class ImageForm(forms.ModelForm):
171 """Form used for editing an Image."""
172 user = forms.ModelChoiceField(queryset=
173 User.objects.annotate(count=Count('chunk')).
174 order_by('-count', 'last_name', 'first_name'), required=False,
175 label=_('Assigned to'))
179 fields = ['title', 'slug', 'user', 'stage']
181 def __init__(self, *args, **kwargs):
182 super(ImageForm, self).__init__(*args, **kwargs)
183 self.fields['slug'].widget.attrs={'class': 'autoslug'}
184 self.fields['title'].widget.attrs={'class': 'autoslug-source'}
187 class ReadonlyImageForm(ImageForm):
188 """Form used for not editing an Image."""
190 def __init__(self, *args, **kwargs):
191 super(ReadonlyImageForm, self).__init__(*args, **kwargs)
192 for field in self.fields.values():
193 field.widget.attrs.update({"disabled": "disabled"})
196 class MarkFinalForm(forms.Form):
197 username = forms.CharField(initial=settings.LITERARY_DIRECTOR_USERNAME)
198 comment = forms.CharField(initial=u'Ostateczna akceptacja merytoryczna przez kierownika literackiego.')
199 books = forms.CharField(widget=forms.Textarea, help_text=u'linki do książek w redakcji, po jednym na wiersz')
201 def clean_books(self):
202 books_value = self.cleaned_data['books']
203 slugs = [line.strip().strip('/').split('/')[-1] for line in books_value.split('\n') if line.strip()]
204 books = Book.objects.filter(slug__in=slugs)
205 if len(books) != len(slugs):
206 raise forms.ValidationError(
207 'Incorrect slug(s): %s' % ' '.join(slug for slug in slugs if not Book.objects.filter(slug=slug)))
210 def clean_username(self):
211 username = self.cleaned_data['username']
212 if not User.objects.filter(username=username):
213 raise forms.ValidationError('Invalid username')
217 for book in self.cleaned_data['books']:
218 for chunk in book.chunk_set.all():
219 src = chunk.head.materialize()
222 author=User.objects.get(username=self.cleaned_data['username']),
223 description=self.cleaned_data['comment'],
224 tags=[Chunk.tag_model.objects.get(slug='editor-proofreading')],
229 class PublishOptionsForm(forms.Form):
230 days = forms.IntegerField(label=u'po ilu dniach udostępnienić (0 = od razu)', min_value=0, initial=0)
231 beta = forms.BooleanField(label=u'Opublikuj na wersji testowej', required=False)