Only formalities.
[wolnelektury.git] / src / picture / forms.py
1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 from django import forms
5 from picture.models import Picture
6
7
8 class PictureImportForm(forms.Form):
9     picture_xml_file = forms.FileField(required=False)
10     picture_xml = forms.CharField(required=False)
11     picture_image_file = forms.FileField(required=False)
12     picture_image_data = forms.CharField(required=False)
13
14     def clean(self):
15         from base64 import b64decode
16         from django.core.files.base import ContentFile
17
18         if not self.cleaned_data['picture_xml_file']:
19             if self.cleaned_data['picture_xml']:
20                 self.cleaned_data['picture_xml_file'] = \
21                         ContentFile(self.cleaned_data['picture_xml'].encode('utf-8'))
22             else:
23                 raise forms.ValidationError('Proszę dostarczyć XML.')
24
25         if not self.cleaned_data['picture_image_file']:
26             if self.cleaned_data['picture_image_data']:
27                 self.cleaned_data['picture_image_file'] = \
28                         ContentFile(b64decode(
29                                 self.cleaned_data['picture_image_data']))
30             else:
31                 raise forms.ValidationError('Proszę dostarczyć obraz.')
32
33         return super(PictureImportForm, self).clean()
34
35     def save(self, commit=True, **kwargs):
36         return Picture.from_xml_file(
37             self.cleaned_data['picture_xml_file'], image_file=self.cleaned_data['picture_image_file'],
38             overwrite=True, **kwargs)