Oops #2
[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=r'[0-9\.\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"Split as new publication")
79     fulltext = forms.CharField(widget=forms.HiddenInput(), required=False)
80     splittext = forms.CharField(widget=forms.HiddenInput(), required=False)
81
82 class DublinCoreForm(forms.Form):
83     about = forms.URLField(verify_exists=False)
84     author = PersonField()
85     title = forms.CharField()
86     epochs = ListField()
87     kinds = ListField()
88     genres = ListField()
89     created_at = forms.DateField()
90     released_to_public_domain_at = forms.DateField(required=False)
91     editors = ListField(widget=forms.Textarea, required=False, converter=person_conv)
92     translators = ListField(widget=forms.Textarea, required=False, converter=person_conv)
93     technical_editors = ListField(widget=forms.Textarea, required=False, converter=person_conv)
94     publisher = forms.CharField()
95     source_name = forms.CharField(widget=forms.Textarea, required=False)
96     source_url = forms.URLField(verify_exists=False, required=False)
97     url = forms.URLField(verify_exists=False)
98     parts = ListField(required=False)
99     license = forms.CharField(required=False)
100     license_description = forms.CharField(widget=forms.Textarea, required=False)
101     
102     commit_message = forms.CharField(required=False, widget=forms.HiddenInput)
103     
104     def __init__(self, *args, **kwargs):
105         info = kwargs.pop('info', None)        
106         super(DublinCoreForm, self).__init__(*args, **kwargs)
107         
108         if isinstance(info, dcparser.BookInfo):
109             vdict = info.to_dict()
110             for name in self.fields.keys():
111                 if vdict.has_key(name):
112                     self.fields[name].initial = vdict[name]