f7fcf07e040a185fdb06401ca1569caa4618a14d
[redakcja.git] / apps / explorer / forms.py
1 from django import forms
2
3 from lxml import etree
4 from librarian import dcparser
5
6 from explorer import models
7
8 class BookForm(forms.Form):
9     content = forms.CharField(widget=forms.Textarea)
10     message = forms.CharField(required=False)
11
12 class ImageFoldersForm(forms.Form):
13     folders = forms.ChoiceField(required=False)
14     
15     def __init__(self, *args, **kwargs):
16         super(ImageFoldersForm, self).__init__(*args, **kwargs)
17         self.fields['folders'].choices = [('', '-- Wybierz folder z obrazkami --')] + [(fn, fn) for fn in models.get_image_folders()]
18
19
20 class DublinCoreForm(forms.Form):
21     wiki_url = forms.URLField(verify_exists=False)
22     author = forms.CharField()
23     title = forms.CharField()
24     epoch = forms.CharField()
25     kind = forms.CharField()
26     genre = forms.CharField()
27     created_at = forms.DateField()
28     released_to_public_domain_at = forms.DateField()
29     translator = forms.CharField(required=False)
30     technical_editor = forms.CharField(required=False)
31     publisher = forms.CharField()
32     source_name = forms.CharField(widget=forms.Textarea)
33     source_url = forms.URLField(verify_exists=False)
34     url = forms.URLField(verify_exists=False)
35     parts = forms.CharField(widget=forms.Textarea, required=False)
36     license = forms.CharField(required=False)
37     license_description = forms.CharField(widget=forms.Textarea, required=False)
38     
39     def __init__(self, *args, **kwargs):
40         text = None
41         if 'text' in kwargs:
42             text = kwargs.pop('text')
43         
44         super(DublinCoreForm, self).__init__(*args, **kwargs)
45         
46         if text is not None:
47             book_info = dcparser.BookInfo.from_string(text)
48             for name, value in book_info.to_dict().items():
49                 self.fields[name].initial = value
50     
51     def save(self, repository, path):
52         file_contents = repository.get_file(path).data()
53         doc = etree.fromstring(file_contents)
54                 
55         book_info = dcparser.BookInfo()
56         for name, value in self.cleaned_data.items():
57             if value is not None and value != '':
58                 setattr(book_info, name, value)
59         rdf = etree.XML(book_info.to_xml())
60         
61         old_rdf = doc.getroottree().find('//{http://www.w3.org/1999/02/22-rdf-syntax-ns#}RDF')
62         old_rdf.getparent().remove(old_rdf)
63         doc.insert(0, rdf)
64         repository.add_file(path, unicode(etree.tostring(doc), 'utf-8'))
65