]> git.openstreetmap.org Git - osqa.git/blob - forum/settings/forms.py
Adds custom header and footer, and a preview mechanism.
[osqa.git] / forum / settings / forms.py
1 import os
2 from string import strip
3 from django import forms
4 from forum.settings.base import Setting
5 from django.utils.translation import ugettext as _
6 from django.core.files.storage import FileSystemStorage
7
8 class DummySetting:
9     pass
10
11 class UnfilteredField(forms.CharField):
12     def clean(self, value):
13             return value
14
15
16 class SettingsSetForm(forms.Form):
17     def __init__(self, set, data=None, unsaved=None, *args, **kwargs):
18         initial = dict([(setting.name, setting.value) for setting in set])
19
20         if unsaved:
21             initial.update(unsaved)
22
23         super(SettingsSetForm, self).__init__(data, initial=initial, *args, **kwargs)
24
25         for setting in set:
26             widget = setting.field_context.get('widget', None)
27
28             if widget is forms.RadioSelect or isinstance(widget, forms.RadioSelect):
29                 field = forms.ChoiceField(**setting.field_context)
30             elif isinstance(setting, (Setting.emulators.get(str, DummySetting), Setting.emulators.get(unicode, DummySetting))):
31                 if not setting.field_context.get('widget', None):
32                     setting.field_context['widget'] = forms.TextInput(attrs={'class': 'longstring'})
33                 field = forms.CharField(**setting.field_context)
34             elif isinstance(setting, Setting.emulators.get(float, DummySetting)):
35                 field = forms.FloatField(**setting.field_context)
36             elif isinstance(setting, Setting.emulators.get(int, DummySetting)):
37                 field = forms.IntegerField(**setting.field_context)
38             elif isinstance(setting, Setting.emulators.get(bool, DummySetting)):
39                 field = forms.BooleanField(**setting.field_context)
40             else:
41                 field = UnfilteredField(**setting.field_context)
42
43             self.fields[setting.name] = field
44
45         self.set = set
46
47     def as_table(self):
48         return self._html_output(
49                 u'<tr><th>%(label)s' + ('<br /><a class="fieldtool context" href="#">%s</a><span class="sep">|</span><a class="fieldtool default" href="#">%s</a></th>' % (
50                     _('context'), _('default'))) + u'<td>%(errors)s%(field)s%(help_text)s</td>',
51                 u'<tr><td colspan="2">%s</td></tr>', '</td></tr>', u'<br />%s', False)
52
53     def save(self):
54         for setting in self.set:
55             setting.set_value(self.cleaned_data[setting.name])
56
57 class ImageFormWidget(forms.Widget):
58     def render(self, name, value, attrs=None):
59         return """
60             <img src="%(value)s" /><br />
61             %(change)s: <input type="file" name="%(name)s" />
62             <input type="hidden" name="%(name)s_old" value="%(value)s" />
63             """ % {'name': name, 'value': value, 'change': _('Change this:')}
64
65     def value_from_datadict(self, data, files, name):
66         if name in files:
67             f = files[name]
68
69             # check file type
70             file_name_suffix = os.path.splitext(f.name)[1].lower()
71
72             if not file_name_suffix in ('.jpg', '.jpeg', '.gif', '.png', '.bmp', '.tiff', '.ico'):
73                 raise Exception('File type not allowed')
74
75             from forum.settings import UPFILES_FOLDER, UPFILES_ALIAS
76
77             storage = FileSystemStorage(str(UPFILES_FOLDER), str(UPFILES_ALIAS))
78             new_file_name = storage.save(f.name, f)
79             return str(UPFILES_ALIAS) + new_file_name
80         else:
81             if "%s_old" % name in data:
82                 return data["%s_old" % name]
83             elif name in data:
84                 return data[name]
85
86 class StringListWidget(forms.Widget):
87     def render(self, name, value, attrs=None):
88         ret = ""
89         for s in value:
90             ret += """
91             <div class="string-list-input">
92                 <input type="text" name="%(name)s" value="%(value)s" />
93                 <button class="string_list_widget_button">-</button>
94             </div>
95             """  % {'name': name, 'value': s}
96
97         return """
98             <div class="string_list_widgets">
99                 %(ret)s
100                 <div><button name="%(name)s" class="string_list_widget_button add">+</button></div>
101             </div>
102             """ % dict(name=name, ret=ret)
103
104     def value_from_datadict(self, data, files, name):
105         if 'submit' in data:
106             return data.getlist(name)
107         else:
108             return data[name]
109
110 class CommaStringListWidget(forms.Textarea):
111     def value_from_datadict(self, data, files, name):
112         if 'submit' in data:
113             return map(strip, data[name].split(','))
114         else:
115             return ', '.join(data[name])    
116
117
118
119