Skip to content

Instantly share code, notes, and snippets.

@hirokiky
Created November 11, 2012 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hirokiky/4054462 to your computer and use it in GitHub Desktop.
Save hirokiky/4054462 to your computer and use it in GitHub Desktop.
Django's widget verbose_radioselect
from django import forms
from django.forms import widgets
from django.utils.translation import ugettext_lazy
from django.utils.encoding import force_unicode
from django.utils.html import escape, conditional_escape
from django.utils.safestring import mark_safe
class InlineRadioInput(widgets.RadioInput):
def render(self, name=None, value=None, attrs=None, choices=()):
name = name or self.name
value = value or self.value
attrs = attrs or self.attrs
choice_label = conditional_escape(force_unicode(self.choice_label))
return mark_safe(u'%s %s' % (self.tag(), choice_label))
class VerboseRadioFieldRenderer(widgets.RadioFieldRenderer):
def __init__(self, name, value, attrs, verbosechoices):
self.name, self.value, self.attrs = name, value, attrs
self.verbosechoices = verbosechoices
def __iter__(self):
for i, (choice, template) in enumerate(self.verbosechoices):
yield InlineRadioInput(self.name, self.value, self.attrs.copy(), choice, i), template
def __getitem__(self, idx):
verbosechoice = self.verbosechoice[idx] # Let the IndexError propogate
choice, template = verbosechoice
return InlineRadioInput(self.name, self.value, self.attrs.copy(), choice, idx), template
def render(self):
return mark_safe(u'<ul>\n%s\n</ul>' % u'\n'.join([u'<li>%s: %s</li>'
% (force_unicode(w), t) for w, t in self]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment