2 from string import strip
3 from django import forms
4 from base import Setting
5 from django.utils.translation import ugettext as _
6 from django.core.files.storage import FileSystemStorage
11 class UnfilteredField(forms.CharField):
12 def clean(self, value):
16 class SettingsSetForm(forms.Form):
17 def __init__(self, set, data=None, *args, **kwargs):
19 data = dict([(setting.name, setting.value) for setting in set])
21 super(SettingsSetForm, self).__init__(data, *args, **kwargs)
24 if isinstance(setting, (Setting.emulators.get(str, DummySetting), Setting.emulators.get(unicode, DummySetting))):
25 field = forms.CharField(**setting.field_context)
26 elif isinstance(setting, Setting.emulators.get(float, DummySetting)):
27 field = forms.FloatField(**setting.field_context)
28 elif isinstance(setting, Setting.emulators.get(int, DummySetting)):
29 field = forms.IntegerField(**setting.field_context)
30 elif isinstance(setting, Setting.emulators.get(bool, DummySetting)):
31 field = forms.BooleanField(**setting.field_context)
33 field = UnfilteredField(**setting.field_context)
35 self.fields[setting.name] = field
40 for setting in self.set:
41 setting.set_value(self.cleaned_data[setting.name])
43 class ImageFormWidget(forms.Widget):
44 def render(self, name, value, attrs=None):
46 <img src="%(value)s" /><br />
47 %(change)s: <input type="file" name="%(name)s" />
48 <input type="hidden" name="%(name)s_old" value="%(value)s" />
49 """ % {'name': name, 'value': value, 'change': _('Change this:')}
51 def value_from_datadict(self, data, files, name):
56 file_name_suffix = os.path.splitext(f.name)[1].lower()
58 if not file_name_suffix in ('.jpg', '.jpeg', '.gif', '.png', '.bmp', '.tiff', '.ico'):
59 raise Exception('File type not allowed')
61 from forum.settings import UPFILES_FOLDER, UPFILES_ALIAS
63 storage = FileSystemStorage(str(UPFILES_FOLDER), str(UPFILES_ALIAS))
64 new_file_name = storage.save(f.name, f)
65 return str(UPFILES_ALIAS) + new_file_name
67 if "%s_old" % name in data:
68 return data["%s_old" % name]
72 class StringListWidget(forms.Widget):
73 def render(self, name, value, attrs=None):
78 <input type="text" name="%(name)s" value="%(value)s" />
79 <button class="string_list_widget_button">-</button>
81 """ % {'name': name, 'value': s}
84 <div class="string_list_widgets">
86 <div><button name="%(name)s" class="string_list_widget_button add">+</button></div>
88 """ % dict(name=name, ret=ret)
90 def value_from_datadict(self, data, files, name):
92 return data.getlist(name)
96 class CommaStringListWidget(forms.Textarea):
97 def value_from_datadict(self, data, files, name):
99 return map(strip, data[name].split(','))
101 return ', '.join(data[name])