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     template = forms.ModelChoiceField(Template.objects, required=False)
 
  22         exclude = ['parent', 'parent_number', 'project', 'gallery', 'public']
 
  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)
 
  31         super(DocumentCreateForm, self).clean()
 
  32         template = self.cleaned_data['template']
 
  33         self.cleaned_data['gallery'] = self.cleaned_data['slug']
 
  35         if template is not None:
 
  36             self.cleaned_data['text'] = template.content
 
  38         if not self.cleaned_data.get("text"):
 
  39             self._errors["template"] = self.error_class([_("You must select a template")])
 
  41         return self.cleaned_data
 
  44 class DocumentsUploadForm(forms.Form):
 
  46         Form used for uploading new documents.
 
  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'}))
 
  53         file = self.cleaned_data['file']
 
  57             z = self.cleaned_data['zip'] = zipfile.ZipFile(file)
 
  58         except zipfile.BadZipfile:
 
  59             raise forms.ValidationError("Should be a ZIP file.")
 
  61             raise forms.ValidationError("ZIP file corrupt.")
 
  63         return self.cleaned_data
 
  66 class ChunkForm(forms.ModelForm):
 
  68         Form used for editing a chunk.
 
  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')) 
 
  77         fields = ['title', 'slug', 'gallery_start', 'user', 'stage']
 
  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'}
 
  87         slug = self.cleaned_data['slug']
 
  89             chunk = Chunk.objects.get(book=self.instance.book, slug=slug)
 
  90         except Chunk.DoesNotExist:
 
  92         if chunk == self.instance:
 
  94         raise forms.ValidationError(_('Chunk with this slug already exists'))
 
  97 class ChunkAddForm(ChunkForm):
 
  99         Form used for adding a chunk to a document.
 
 102     def clean_slug(self):
 
 103         slug = self.cleaned_data['slug']
 
 105             user = Chunk.objects.get(book=self.instance.book, slug=slug)
 
 106         except Chunk.DoesNotExist:
 
 108         raise forms.ValidationError(_('Chunk with this slug already exists'))
 
 111 class BookAppendForm(forms.Form):
 
 113         Form for appending a book to another book.
 
 114         It means moving all chunks from book A to book B and deleting A.
 
 116     append_to = forms.ModelChoiceField(queryset=Book.objects.all(),
 
 117             label=_("Append to"))
 
 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)
 
 125 class BookForm(forms.ModelForm):
 
 126     """Form used for editing a Book."""
 
 130         exclude = ['project']
 
 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"})
 
 139 class ReadonlyBookForm(BookForm):
 
 140     """Form used for not editing a Book."""
 
 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})
 
 149 class ChooseMasterForm(forms.Form):
 
 151         Form used for fixing the chunks in a book.
 
 154     master = forms.ChoiceField(choices=((m, m) for m in MASTERS))