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