]> git.openstreetmap.org Git - osqa.git/blob - forum/settings/forms.py
Reduces the amount of connections to the cache server.
[osqa.git] / forum / settings / forms.py
1 import os
2 import socket
3 from string import strip
4 from django import forms
5 from base import Setting
6 from django.utils.translation import ugettext as _
7 from django.core.files.storage import FileSystemStorage
8
9 class DummySetting:
10     pass
11
12 class UnfilteredField(forms.CharField):
13     def clean(self, value):
14             return value
15
16
17 class SettingsSetForm(forms.Form):
18     def __init__(self, set, data=None, *args, **kwargs):
19         if data is None:
20             data = dict([(setting.name, setting.value) for setting in set])
21
22         super(SettingsSetForm, self).__init__(data, *args, **kwargs)
23
24         for setting in set:
25             if isinstance(setting, (Setting.emulators.get(str, DummySetting), Setting.emulators.get(unicode, DummySetting))):
26                 if not setting.field_context.get('widget', None):
27                     setting.field_context['widget'] = forms.TextInput(attrs={'class': 'longstring'})
28                 field = forms.CharField(**setting.field_context)
29             elif isinstance(setting, Setting.emulators.get(float, DummySetting)):
30                 field = forms.FloatField(**setting.field_context)
31             elif isinstance(setting, Setting.emulators.get(int, DummySetting)):
32                 field = forms.IntegerField(**setting.field_context)
33             elif isinstance(setting, Setting.emulators.get(bool, DummySetting)):
34                 field = forms.BooleanField(**setting.field_context)
35             else:
36                 field = UnfilteredField(**setting.field_context)
37
38             self.fields[setting.name] = field
39
40         self.set = set
41
42     def as_table(self):
43         return self._html_output(
44                 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>' % (
45                     _('context'), _('default'))) + u'<td>%(errors)s%(field)s%(help_text)s</td>',
46                 u'<tr><td colspan="2">%s</td></tr>', '</td></tr>', u'<br />%s', False)
47
48     def save(self):
49         for setting in self.set:
50             setting.set_value(self.cleaned_data[setting.name])
51
52 class ImageFormWidget(forms.Widget):
53     def render(self, name, value, attrs=None):
54         return """
55             <img src="%(value)s" /><br />
56             %(change)s: <input type="file" name="%(name)s" />
57             <input type="hidden" name="%(name)s_old" value="%(value)s" />
58             """ % {'name': name, 'value': value, 'change': _('Change this:')}
59
60     def value_from_datadict(self, data, files, name):
61         if name in files:
62             f = files[name]
63
64             # check file type
65             file_name_suffix = os.path.splitext(f.name)[1].lower()
66
67             if not file_name_suffix in ('.jpg', '.jpeg', '.gif', '.png', '.bmp', '.tiff', '.ico'):
68                 raise Exception('File type not allowed')
69
70             from forum.settings import UPFILES_FOLDER, UPFILES_ALIAS
71
72             storage = FileSystemStorage(str(UPFILES_FOLDER), str(UPFILES_ALIAS))
73             new_file_name = storage.save(f.name, f)
74             return str(UPFILES_ALIAS) + new_file_name
75         else:
76             if "%s_old" % name in data:
77                 return data["%s_old" % name]
78             elif name in data:
79                 return data[name]
80
81 class StringListWidget(forms.Widget):
82     def render(self, name, value, attrs=None):
83         ret = ""
84         for s in value:
85             ret += """
86             <div class="string-list-input">
87                 <input type="text" name="%(name)s" value="%(value)s" />
88                 <button class="string_list_widget_button">-</button>
89             </div>
90             """  % {'name': name, 'value': s}
91
92         return """
93             <div class="string_list_widgets">
94                 %(ret)s
95                 <div><button name="%(name)s" class="string_list_widget_button add">+</button></div>
96             </div>
97             """ % dict(name=name, ret=ret)
98
99     def value_from_datadict(self, data, files, name):
100         if 'submit' in data:
101             return data.getlist(name)
102         else:
103             return data[name]
104
105 class CommaStringListWidget(forms.Textarea):
106     def value_from_datadict(self, data, files, name):
107         if 'submit' in data:
108             return map(strip, data[name].split(','))
109         else:
110             return ', '.join(data[name])    
111
112
113 class IPListField(forms.CharField):
114     def clean(self, value):
115         ips = [ip.strip() for ip in value.strip().strip(',').split(',')]
116         iplist = []
117
118         if len(ips) < 1:
119             raise forms.ValidationError(_('Please input at least one ip address'))    
120
121         for ip in ips:
122             try:
123                 socket.inet_aton(ip)
124             except socket.error:
125                 raise forms.ValidationError(_('Invalid ip address: %s' % ip))
126
127             if not len(ip.split('.')) == 4:
128                 raise forms.ValidationError(_('Please use the dotted quad notation for the ip addresses'))
129
130             iplist.append(ip)
131
132         return iplist
133
134 class MaintenanceModeForm(forms.Form):
135     ips = IPListField(label=_('Allow ips'),
136                       help_text=_('Comma separated list of ips allowed to access the site while in maintenance'),
137                       required=True,
138                       widget=forms.TextInput(attrs={'class': 'longstring'}))
139
140     message = forms.CharField(label=_('Message'),
141                               help_text=_('A message to display to your site visitors while in maintainance mode'),
142                               widget=forms.Textarea)
143
144
145