Style fixes, add missing docstring, fix some wrong calls to super classes and removal...
[Melange.git] / app / soc / views / helper / widgets.py
blob317d98eeb1139e448c9cb5b23bc7c752660bb673
1 #!/usr/bin/python2.5
3 # Copyright 2008 the Melange authors.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 """Custom widgets used for form fields.
18 """
20 __authors__ = [
21 '"Pawel Solyga" <pawel.solyga@gmail.com>',
22 '"Sverre Rabbelier" <sverre@rabbelier.nl>',
26 from django import forms
27 from django.forms import util
28 from django.forms import widgets
29 from django.utils import html
30 from django.utils import simplejson
31 from django.utils import safestring
33 from soc.logic import dicts
36 class ReadOnlyInput(forms.widgets.Input):
37 """Read only input widget.
38 """
40 input_type = 'text'
42 def render(self, name, value, attrs=None):
43 """Render ReadOnlyInput widget as HTML.
44 """
46 attrs['readonly'] = 'readonly'
47 attrs['class'] = 'plaintext'
49 return super(ReadOnlyInput, self).render(name, value, attrs)
52 class PlainTextWidget(forms.widgets.Widget):
53 """Read only input widget.
54 """
56 def render(self, name, value, attrs=None):
57 """Render ReadOnlyInput widget as HTML.
58 """
60 return str(value) if value else ""
63 class FullTinyMCE(forms.widgets.Textarea):
64 """TinyMCE widget.
66 Requires to include tiny_mce_src.js in your template. Widget can be
67 customized by overwriting or adding extra options to mce_settings
68 dictionary
70 You can set TinyMCE widget for particular form field using code below:
71 class ExampleForm(helper.forms.BaseForm):
72 content = forms.fields.CharField(widget=helper.widgets.TinyMCE())
74 You can include tiny_mce.js in your template using:
75 {% block scripts %}
76 <script type="text/javascript" src="/tiny_mce/tiny_mce.js"></script>
77 {% endblock %}
78 """
80 features1 = ("bold,italic,underline,strikethrough,blockquote,|,"
81 ",justifyleft,justifycenter,justifyright,justifyfull,|,"
82 "formatselect")
84 features2 = ("newdocument,|,bullist,numlist,|,outdent,indent,|,undo,redo,|"
85 ",link,unlink,anchor,image,cleanup,help,code,hr,removeformat,visualaid,|,"
86 "sub,sup,|,charmap,"
87 "")
89 DEF_MCE_SETTINGS = {
90 'mode': "exact",
91 'theme': "advanced",
92 'theme_advanced_buttons1': features1,
93 'theme_advanced_buttons2': features2,
94 'theme_advanced_buttons3': '',
95 'theme_advanced_resizing': True,
96 'theme_advanced_toolbar_location': "top",
97 'theme_advanced_statusbar_location': "bottom",
98 'theme_advanced_path' : False,
99 'theme_advanced_toolbar_align': "left",
100 'relative_urls': 0,
101 'remove_script_host': 0,
105 TINY_MCE_HTML_FMT = u'''\
106 <textarea %(attrs)s>%(value)s</textarea>
107 <script type="text/javascript">
108 tinyMCE.init(%(settings_json)s)
109 </script>'''
111 def __init__(self, mce_settings=None, *args, **kwargs):
112 """Initialize TinyMCE widget with default or customized settings.
114 Args:
115 mce_settings: dict with TinyMCE widget settings
116 *args, **kwargs: passed through to parent __init__() constructor
119 super(FullTinyMCE, self).__init__(*args, **kwargs)
120 self.mce_settings = self.DEF_MCE_SETTINGS
122 def render(self, name, value, attrs=None):
123 """Render TinyMCE widget as HTML.
125 if value is None:
126 value = ''
127 value = util.smart_unicode(value)
128 final_attrs = self.build_attrs(attrs, name=name)
130 self.mce_settings['elements'] = "id_%s" % name
132 # convert mce_settings from dict to JSON
133 mce_json = simplejson.JSONEncoder().encode(self.mce_settings)
135 return safestring.mark_safe(self.TINY_MCE_HTML_FMT %
136 {'attrs': widgets.flatatt(final_attrs),
137 'value': html.escape(value),
138 'settings_json': mce_json})
141 class TinyMCE(FullTinyMCE):
142 """Regular version of TinyMce
145 def __init__(self, *args, **kwargs):
149 super(TinyMCE, self).__init__(*args, **kwargs)
150 keys = ['mode', 'theme', 'theme_advanced_toolbar_location',
151 'theme_advanced_toolbar_align', 'relative_urls',
152 'remove_script_host']
153 self.mce_settings = dicts.filter(self.mce_settings, keys)
155 class ReferenceField(forms.CharField):
156 """Widget for selecting a reference to an Entity.
159 def __init__(self, reference_url, filter=None, filter_fields=None,
160 *args, **kwargs):
161 """Initializes the widget with the specified url and filter.
164 self.rf = {}
165 self.rf['reference_url'] = reference_url
166 self.rf['filter'] = filter if filter else []
167 self.rf['filter_fields'] = filter_fields if filter_fields else {}
168 super(ReferenceField, self).__init__(*args, **kwargs)
171 class AgreementField(widgets.Widget):
172 """Widget for selecting a reference to an Entity.
175 HTML_CODE = """
176 <span style="width:450px" colspan="4">
177 <div id="ToS" style="overflow:auto;height:500px">
178 %(text)s
179 </div>
180 </span>
181 %(url)s
184 def __init__(self, *args, **kwargs):
185 self.text = "No Agreement Text Specified"
186 self.url = ""
187 super(AgreementField, self).__init__(*args, **kwargs)
189 def render(self, name, value, attrs=None):
190 """HTML renderer for Agreement field.
192 url_text = '<a href="%s" target="_blank">Full Text</a>'
193 url = url_text % self.url if self.url else ""
194 value = self.text.replace('\n', '<BR />')
195 result = self.HTML_CODE % {'url': url, 'text': value}
196 return result