]> git.openstreetmap.org Git - osqa.git/blob - forum/settings/forms.py
OSQA - 19
[osqa.git] / forum / settings / forms.py
1 import os
2 from django import forms
3 from base import Setting, StringSetting, IntegerSetting, BoolSetting, FloatSetting
4 from django.utils.translation import ugettext as _
5 from django.core.files.storage import FileSystemStorage
6
7 class SettingsSetForm(forms.Form):
8     def __init__(self, set, data=None, *args, **kwargs):
9         if data is None:
10             data = dict([(setting.name, setting.value) for setting in set])
11
12         super(SettingsSetForm, self).__init__(data, *args, **kwargs)
13
14         for setting in set:
15             if isinstance(setting, StringSetting):
16                 field = forms.CharField(**setting.field_context)
17             elif isinstance(setting, FloatSetting):
18                 field = forms.FloatField(**setting.field_context)
19             elif isinstance(setting, IntegerSetting):
20                 field = forms.IntegerField(**setting.field_context)
21             elif isinstance(setting, BoolSetting):
22                 field = forms.BooleanField(**setting.field_context)
23             else:
24                 field = forms.CharField(**setting.field_context)
25
26             self.fields[setting.name] = field
27
28         self.set = set
29
30     def save(self):
31         for setting in self.set:
32             setting.set_value(self.cleaned_data[setting.name])
33
34 class ImageFormWidget(forms.Widget):
35     def render(self, name, value, attrs=None):
36         return """
37             <img src="%(value)s" /><br />
38             %(change)s: <input type="file" name="%(name)s" />
39             <input type="hidden" name="%(name)s_old" value="%(value)s" />
40             """ % {'name': name, 'value': value, 'change': _('Change this:')}
41
42     def value_from_datadict(self, data, files, name):
43         if name in files:
44             f = files[name]
45
46             # check file type
47             file_name_suffix = os.path.splitext(f.name)[1].lower()
48
49             if not file_name_suffix in ('.jpg', '.jpeg', '.gif', '.png', '.bmp', '.tiff', '.ico'):
50                 raise Exception('File type not allowed')
51
52             from forum.settings import UPFILES_FOLDER, UPFILES_ALIAS
53
54             storage = FileSystemStorage(str(UPFILES_FOLDER), str(UPFILES_ALIAS))
55             new_file_name = storage.save(f.name, f)
56             return str(UPFILES_ALIAS) + new_file_name
57         else:
58             if "%s_old" % name in data:
59                 return data["%s_old" % name]
60             elif name in data:
61                 return data[name]
62
63