Skip to content

Instantly share code, notes, and snippets.

@dustinsmith1024
Created December 30, 2011 06:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dustinsmith1024/1538180 to your computer and use it in GitHub Desktop.
Save dustinsmith1024/1538180 to your computer and use it in GitHub Desktop.
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