Custom radio field rendering with django newforms
I'm trying to replicate the look and feel of an existing site, which has a grouping of radio buttons that isn't easy to replicate with the built-in django methods. To really replicate it I need to render each button seperately. There's a class deep inside the RadioButton widget that acts as a list of buttons, which would be perfect, but there's no accessor for it built into the current forms. Luckily, it's easy to get to.
This means that inside the form, I can render each radio button at will using, e.g.,
This also gives me a handle to change the rendering of the actual <input> elements. I needed some javascript, but the RadioSelect widget doesn't pass its attrs all the way down to the input elements. This part is a little ugly, but I used regexps to insert an attribute into the rendered element:
While editing the rendered content is a bit ooky, it's the only way I've been able to find to add javascript for now.
class ListReqStep1(forms.Form):
mail_type = forms.ChoiceField(choices=(
('newwg', 'Create new WG email list at ietf.org'),
('movewg', 'Move existing WG email list to ietf.org'),
('closewg', 'Close existing WG email list at ietf.org'),
('newnon', 'Create new non-WG email list at selected domain above'),
('movenon', 'Move existing non-WG email list to selected domain above'),
('closenon', 'Close existing non-WG email list at selected domain above'),
), widget=forms.RadioSelect())
def mail_type_fields(self):
field = self['mail_type']
return field.as_widget(field.field.widget)
This means that inside the form, I can render each radio button at will using, e.g.,
<h2>Working Group Fields</h2>
{{ form.mail_type_fields.0 }}<br>
{{ form.mail_type_fields.1 }}<br>
{{ form.mail_type_fields.2 }}<br>
<h2>Non-Working Group Fields</h2>
{{ form.mail_type_fields.3 }}<br>
{{ form.mail_type_fields.4 }}<br>
{{ form.mail_type_fields.5 }}<br>
This also gives me a handle to change the rendering of the actual <input> elements. I needed some javascript, but the RadioSelect widget doesn't pass its attrs all the way down to the input elements. This part is a little ugly, but I used regexps to insert an attribute into the rendered element:
def mail_type_fields(self):
field = self['mail_type']
# RadioSelect() doesn't pass its attributes through to the <input>
# elements, so in order to get the javascript onClick we add it here.
return [re.sub(r'input ','input onClick="activate_widgets()" ',str(i))
for i in field.as_widget(field.field.widget)]
While editing the rendered content is a bit ooky, it's the only way I've been able to find to add javascript for now.

1 Comments:
Is there a more generic way to do this, I have a form with many radio buttons, and don't like the built-in "ul li" stuff...
By
Unknown, at 9:30 AM
Post a Comment
<< Home