restore old forms (sciezki kopernika)
[edumed.git] / catalogue / forms.py
1 # -*- coding: utf-8 -*-
2 import json
3 import os.path
4 import shutil
5 import urllib
6 from tempfile import mkdtemp
7
8 from django.forms import Form, CharField
9
10 from librarian import IOFile
11 from catalogue.models import Lesson
12
13
14 class LessonImportForm(Form):
15     lesson_xml = CharField()
16     gallery_url = CharField(required=False)
17     attachments = CharField(required=False)
18
19     def save(self):
20         temp_dir = mkdtemp()
21         attachment_names = json.loads(self.cleaned_data['attachments'])
22         attachments = {}
23         remote_gallery_url = self.cleaned_data['gallery_url']
24         if remote_gallery_url and attachment_names:
25             for attachment_name in attachment_names:
26                 attachment_url = ('%s%s' % (remote_gallery_url, attachment_name)).encode('utf-8')
27                 temp_filename = os.path.join(temp_dir, attachment_name)
28                 urllib.urlretrieve(attachment_url, temp_filename)
29                 attachments[attachment_name] = IOFile.from_filename(temp_filename)
30
31         lesson = Lesson.publish(
32             IOFile.from_string(self.cleaned_data['lesson_xml'], attachments=attachments))
33         if os.path.isdir(temp_dir):
34             shutil.rmtree(temp_dir)
35         return lesson