Skip to content

Instantly share code, notes, and snippets.

@austing
Created January 7, 2011 07:08
Show Gist options
  • Save austing/769217 to your computer and use it in GitHub Desktop.
Save austing/769217 to your computer and use it in GitHub Desktop.
customized form rendering in Django: RadioSelect with labels on the left
# forms.py
from django import forms
from django.core import validators
from django.forms.widgets import RadioSelect,HiddenInput
from django.utils.safestring import mark_safe
from django.utils.encoding import StrAndUnicode, force_unicode
from django.utils.html import escape, conditional_escape
class CustomRadioInput(forms.widgets.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'<label%s>%s</label> %s' % (label_for, choice_label, self.tag()))
class CustomRadioRenderer(forms.widgets.RadioFieldRenderer):
def __iter__(self):
for i, choice in enumerate(self.choices):
yield CustomRadioInput(self.name, self.value, self.attrs.copy(), choice, i)
def __getitem__(self, idx):
choice = self.choices[idx] # Let the IndexError propogate
return CustomRadioInput(self.name, self.value, self.attrs.copy(), choice, idx)
def render(self):
return_value = mark_safe(u'\n'.join([u'%s<br>' % force_unicode(w) for w in self]))
return return_value
class CustomRadioSelect(forms.widgets.RadioSelect):
renderer = CustomRadioRenderer
class NewItemForm(forms.Form):
radio_choices = (("new_quote","Add a source"),("new_quote_and_original","Add bilingual source"),("",None))
new = forms.ChoiceField(widget=CustomRadioSelect(),choices=radio_choices)
ordinal = forms.IntegerField(widget=HiddenInput)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment