9541cb02e7a2461ced3203dd6c9bc85f78363d23
[redakcja.git] / apps / explorer / forms.py
1 # -*- coding: utf-8 -*-
2 from django import forms
3
4 from lxml import etree
5 from librarian import dcparser
6 import django.utils
7
8 from explorer import models
9
10 class PersonField(forms.CharField):
11     def clean(self, value):
12         try:
13             return dcparser.Person.from_text( super(PersonField, self).clean(value) )
14         except ValueError, e:
15             raise django.utils.ValidationError(e.message)
16
17 def person_conv(value):
18     if isinstance(value, dcparser.Person):
19         return value
20     elif isinstance(value, basestring):
21         return dcparser.Person.from_text( unicode(value) )
22     else:
23         raise ValueError("Can't convert '%s' to Person object." % value)
24
25 class ListField(forms.Field):
26     def __init__(self, *args, **kwargs):
27         self.convert = kwargs.pop('converter', unicode)
28         if not kwargs.has_key('widget'):
29             kwargs['widget'] = forms.Textarea
30         super(ListField, self).__init__(*args, **kwargs)
31     
32     def _get_initial(self):
33         return self._initial and (u'\n'.join( ( unicode(person) for person in self._initial)))
34
35     def _set_initial(self, value):
36         if value is None:
37             self._initial = None
38         elif isinstance(value, list):
39             self._initial = [ self.convert(e) for e in value ]
40         elif isinstance(value, basestring):
41             self._initial = [ self.convert(e) for e in value.split('\n') ]
42         else:
43             raise ValueError("Invalid value. Must be a list of dcparser.Person or string")    
44
45     initial = property(_get_initial, _set_initial)
46
47     def clean(self, value):
48         super(ListField, self).clean(value)
49         elems = value.split('\n')
50         try:
51             return [self.convert(el) for el in elems]
52         except ValueError, err:
53             raise django.utils.ValidationError(err.message)
54
55 class BookForm(forms.Form):
56     content = forms.CharField(widget=forms.Textarea)
57     commit_message = forms.CharField(required=False)
58
59 class MergeForm(forms.Form):
60     message = forms.CharField(error_messages={'required': 'Please write a merge description.'})
61
62 class BookUploadForm(forms.Form):
63     file = forms.FileField(label='Source OCR file')
64     bookname = forms.RegexField(regex='[\w-]+',  \
65         label='Publication name', help_text='Example: slowacki-beniowski')
66     autoxml = forms.BooleanField(required=False, initial=True, label=u"Generate DublinCore template")
67
68 class ImageFoldersForm(forms.Form):
69     folders = forms.ChoiceField(required=False)
70     
71     def __init__(self, *args, **kwargs):
72         super(ImageFoldersForm, self).__init__(*args, **kwargs)
73         self.fields['folders'].choices = [('', '-- Wybierz folder z obrazkami --')] + [(fn, fn) for fn in models.get_image_folders()]
74
75 class SplitForm(forms.Form):
76     partname = forms.RegexField(regex='[0-9\w-]+',  \
77         label='Part name', help_text='Example: rozdziaƂ-2')
78     autoxml = forms.BooleanField(required=False, initial=False, label=u"Generate DublinCore")
79
80 class DublinCoreForm(forms.Form):
81     about = forms.URLField(verify_exists=False)
82     author = PersonField()
83     title = forms.CharField()
84     epochs = ListField()
85     kinds = ListField()
86     genres = ListField()
87     created_at = forms.DateField()
88     released_to_public_domain_at = forms.DateField(required=False)
89     editors = ListField(widget=forms.Textarea, required=False, converter=person_conv)
90     translators = ListField(widget=forms.Textarea, required=False, converter=person_conv)
91     technical_editors = ListField(widget=forms.Textarea, required=False, converter=person_conv)
92     publisher = forms.CharField()
93     source_name = forms.CharField(widget=forms.Textarea, required=False)
94     source_url = forms.URLField(verify_exists=False, required=False)
95     url = forms.URLField(verify_exists=False)
96     parts = forms.CharField(widget=forms.Textarea, required=False)
97     license = forms.CharField(required=False)
98     license_description = forms.CharField(widget=forms.Textarea, required=False)
99     
100     commit_message = forms.CharField(required=False, widget=forms.HiddenInput)
101     
102     def __init__(self, *args, **kwargs):
103         info = kwargs.pop('info', None)        
104         super(DublinCoreForm, self).__init__(*args, **kwargs)
105         
106         if isinstance(info, dcparser.BookInfo):
107             vdict = info.to_dict()
108             for name in self.fields.keys():
109                 if vdict.has_key(name):
110                     self.fields[name].initial = vdict[name]