1 from django.forms import Textarea
2 from django.utils.safestring import mark_safe
3
4 -class ShortTextarea(Textarea):
5 """
6 Provides a textarea widget which uses a simple js statement to limit the
7 number of chars.
8
9 example usage: widget=ShortTextarea(limit=45, rows=3, cols=15)
10 """
11 - def __init__(self, attrs={}, limit=1024, rows=10, cols=50):
12 super(ShortTextarea, self).__init__(attrs)
13 self.limit = int(limit)
14 self.rows = int(rows)
15 self.cols = int(cols)
16
17 - def render(self, name, value, attrs=None):
18 output = ['<p>']
19 chars_used = 0
20 if value:
21 chars_used = len(value)
22
23 if chars_used > self.limit:
24 alert_truncate = "true"
25 else:
26 alert_truncate = "false"
27
28 js_snip = 'limit_to(this, %d, "%s_chars_used", %s);' % (self.limit, name, alert_truncate)
29 attrs = {
30 'rows': '%d' % self.rows,
31 'cols': '%d' % self.cols,
32 'id': 'id_%s' % name,
33 'onKeyUp': js_snip,
34 'onKeyDown': js_snip,
35 'onChange': js_snip,
36 }
37 output.append(super(ShortTextarea, self).render(name, value, attrs))
38 output.append("</p>")
39 if chars_used > self.limit:
40 output.append("<p style='color:red;font-weight:bold;'>Editing this field will truncate text to %d characters</p>" % self.limit)
41 output.append("<p><span id='%s_chars_used'>%d</span> characters of %d limit entered.</p>" % (name, chars_used, self.limit))
42
43 return mark_safe(u''.join(output))
44