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
7 class SettingsSetForm(forms.Form):
8 def __init__(self, set, data=None, *args, **kwargs):
10 data = dict([(setting.name, setting.value) for setting in set])
12 super(SettingsSetForm, self).__init__(data, *args, **kwargs)
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)
24 field = forms.CharField(**setting.field_context)
26 self.fields[setting.name] = field
31 for setting in self.set:
32 setting.set_value(self.cleaned_data[setting.name])
34 class ImageFormWidget(forms.Widget):
35 def render(self, name, value, attrs=None):
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:')}
42 def value_from_datadict(self, data, files, name):
47 file_name_suffix = os.path.splitext(f.name)[1].lower()
49 if not file_name_suffix in ('.jpg', '.jpeg', '.gif', '.png', '.bmp', '.tiff', '.ico'):
50 raise Exception('File type not allowed')
52 from forum.settings import UPFILES_FOLDER, UPFILES_ALIAS
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
58 if "%s_old" % name in data:
59 return data["%s_old" % name]