Updating metadata configuration for editor
[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 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 _
10
11 from catalogue.constants import MASTERS
12 from catalogue.models import Book, Chunk, Template
13
14 class DocumentCreateForm(forms.ModelForm):
15     """
16         Form used for creating new documents.
17     """
18     template = forms.ModelChoiceField(Template.objects, required=False)
19
20     class Meta:
21         model = Book
22         exclude = ['parent', 'parent_number', 'project', 'gallery', 'public']
23
24     def __init__(self, *args, **kwargs):
25         super(DocumentCreateForm, self).__init__(*args, **kwargs)
26         self.fields['slug'].widget.attrs={'class': 'autoslug'}
27         self.fields['title'].widget.attrs={'class': 'autoslug-source'}
28         self.fields['template'].queryset = Template.objects.filter(is_main=True)
29
30     def clean(self):
31         super(DocumentCreateForm, self).clean()
32         template = self.cleaned_data['template']
33         self.cleaned_data['gallery'] = self.cleaned_data['slug']
34
35         if template is not None:
36             self.cleaned_data['text'] = template.content
37
38         if not self.cleaned_data.get("text"):
39             self._errors["template"] = self.error_class([_("You must select a template")])
40
41         return self.cleaned_data
42
43
44 class DocumentsUploadForm(forms.Form):
45     """
46         Form used for uploading new documents.
47     """
48     file = forms.FileField(required=True, label=_('ZIP file'))
49     dirs = forms.BooleanField(label=_('Directories are documents in chunks'),
50             widget = forms.CheckboxInput(attrs={'disabled':'disabled'}))
51
52     def clean(self):
53         file = self.cleaned_data['file']
54
55         import zipfile
56         try:
57             z = self.cleaned_data['zip'] = zipfile.ZipFile(file)
58         except zipfile.BadZipfile:
59             raise forms.ValidationError("Should be a ZIP file.")
60         if z.testzip():
61             raise forms.ValidationError("ZIP file corrupt.")
62
63         return self.cleaned_data
64
65
66 class ChunkForm(forms.ModelForm):
67     """
68         Form used for editing a chunk.
69     """
70     user = forms.ModelChoiceField(queryset=
71         User.objects.annotate(count=Count('chunk')).
72         order_by('last_name', 'first_name'), required=False,
73         label=_('Assigned to')) 
74
75     class Meta:
76         model = Chunk
77         fields = ['title', 'slug', 'gallery_start', 'user', 'stage']
78         exclude = ['number']
79
80     def __init__(self, *args, **kwargs):
81         super(ChunkForm, self).__init__(*args, **kwargs)
82         self.fields['gallery_start'].widget.attrs={'class': 'number-input'}
83         self.fields['slug'].widget.attrs={'class': 'autoslug'}
84         self.fields['title'].widget.attrs={'class': 'autoslug-source'}
85
86     def clean_slug(self):
87         slug = self.cleaned_data['slug']
88         try:
89             chunk = Chunk.objects.get(book=self.instance.book, slug=slug)
90         except Chunk.DoesNotExist:
91             return slug
92         if chunk == self.instance:
93             return slug
94         raise forms.ValidationError(_('Chunk with this slug already exists'))
95
96
97 class ChunkAddForm(ChunkForm):
98     """
99         Form used for adding a chunk to a document.
100     """
101
102     def clean_slug(self):
103         slug = self.cleaned_data['slug']
104         try:
105             user = Chunk.objects.get(book=self.instance.book, slug=slug)
106         except Chunk.DoesNotExist:
107             return slug
108         raise forms.ValidationError(_('Chunk with this slug already exists'))
109
110
111 class BookAppendForm(forms.Form):
112     """
113         Form for appending a book to another book.
114         It means moving all chunks from book A to book B and deleting A.
115     """
116     append_to = forms.ModelChoiceField(queryset=Book.objects.all(),
117             label=_("Append to"))
118
119     def __init__(self, book, *args, **kwargs):
120         ret =  super(BookAppendForm, self).__init__(*args, **kwargs)
121         self.fields['append_to'].queryset = Book.objects.exclude(pk=book.pk)
122         return ret
123
124
125 class BookForm(forms.ModelForm):
126     """Form used for editing a Book."""
127
128     class Meta:
129         model = Book
130         exclude = ['project']
131
132     def __init__(self, *args, **kwargs):
133         ret = super(BookForm, self).__init__(*args, **kwargs)
134         self.fields['slug'].widget.attrs.update({"class": "autoslug"})
135         self.fields['title'].widget.attrs.update({"class": "autoslug-source"})
136         return ret
137
138
139 class ReadonlyBookForm(BookForm):
140     """Form used for not editing a Book."""
141
142     def __init__(self, *args, **kwargs):
143         ret = super(ReadonlyBookForm, self).__init__(*args, **kwargs)
144         for field in self.fields.values():
145             field.widget.attrs.update({"readonly": True})
146         return ret
147
148
149 class ChooseMasterForm(forms.Form):
150     """
151         Form used for fixing the chunks in a book.
152     """
153
154     master = forms.ChoiceField(choices=((m, m) for m in MASTERS))