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