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