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