Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Radio Inputs in Django that don't have LABEL wraps
"""
1. Inherit from the normal RadioInput and copy the RadioInput __unicode__ method. Then change it up how you please:
"""
class RadioInputNoWrap(RadioInput):
def __unicode__(self):
if 'id' in self.attrs:
label_for = ' for="%s_%s"' % (self.attrs['id'], self.index)
else:
label_for = ''
choice_label = conditional_escape(force_unicode(self.choice_label))
return mark_safe(u'%s<label%s>%s</label>' % (self.tag(), label_for, choice_label))
"""
2. Then inherit from RadioSelect.renderer and copy the RadioFieldRenderer __iter__ method and patch it to call our new RadioInputNoWrap widget (you might need to patch __get_item__ as well):
"""
class RadioFieldRendererNoWrap(forms.RadioSelect.renderer):
def __iter__(self):
for i, choice in enumerate(self.choices):
yield RadioInputNoWrap(self.name, self.value, self.attrs.copy(), choice, i)
"""
3. Then when you call the form just specify the new renderer:
"""
radio = forms.ChoiceField(widget=RadioSelect(renderer=RadioFieldRendererNoWrap),
choices=answer_choices,)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment