RadioSelectWithHelpText

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Widget and renderer:

from django import forms
from django.forms.widgets import RadioFieldRenderer

class RadioWithHelpTextFieldRenderer(forms.widgets.RadioFieldRenderer):
	def __init__(self, name, value, attrs, choices, choice_help_text):
		super(RadioWithHelpTextFieldRenderer, self).__init__(name, value, attrs, choices)
		self.choice_help_text = choice_help_text
	
	def render(self):
		from django.utils.encoding import force_unicode
		from django.utils.safestring import mark_safe
		
		return mark_safe(
			u'<ul>\n%s\n</ul>' % u'\n'.join(
				[
					u'<li>%s<small><br />%s</small></li>' % (
						force_unicode(w),
						self.choice_help_text[i]
					) for i, w in enumerate(self)
				]
			)
		)

class RadioSelectWithHelpText(forms.RadioSelect):
	renderer = RadioWithHelpTextFieldRenderer
	
	def __init__(self, *args, **kwargs):
		choice_help_text = kwargs.pop('choice_help_text', ())
		super(RadioSelectWithHelpText, self).__init__(*args, **kwargs)
		self.choice_help_text = choice_help_text
	
	def get_renderer(self, name, value, attrs=None, choices=()):
		if value is None:
			value = ''
		
		from django.utils.encoding import force_unicode
		from itertools import chain
		
		str_value = force_unicode(value)
		final_attrs = self.build_attrs(attrs)
		choices = list(chain(self.choices, choices))
		choice_help_text = self.choice_help_text
		return self.renderer(name, str_value, final_attrs, choices, choice_help_text)

# In your form

class MyFormClass(forms.Form):
	def __init__(self, *args, **kwargs):
		super(MyFormClass, self).__init__(*args, **kwargs)
		
		choices = (
			('a', 'Choice A'),
			('b', 'Choice B'),
			('c', 'Choice C')
		)
		
		choice_help = (
			'Help text for Choice A',
			'Help text for Choice B',
			'Help text for Choice C'
		)
		
		self.fields['kind'].widget = RadioSelectWithHelpText(
			choices = choices,
			choice_help_text = choice_help
		)

More like this

  1. Horizontal RadioSelect widget by gnrfan 1 year, 2 months ago
  2. Rendering radio-buttons with icons instead of labels by jeverling 3 years, 2 months ago
  3. CheckboxMultiSelect with interable checkboxes by pyramids16 6 months, 2 weeks ago
  4. ChoiceField with widget in choice by alfonsopalomares 4 years, 2 months ago
  5. Admin actions as buttons instead of a menu by andybak 3 years, 2 months ago

Comments

(Forgotten your password?)