Code

Ticket #4228: radioselect_renderer.patch

File radioselect_renderer.patch, 2.6 KB (added by SmileyChris, 7 years ago)
  • django/newforms/widgets.py

     
    2020    'HiddenInput', 'MultipleHiddenInput', 
    2121    'FileInput', 'Textarea', 'CheckboxInput', 
    2222    'Select', 'NullBooleanSelect', 'SelectMultiple', 'RadioSelect', 
     23    'RadioFieldRenderer', 
    2324    'CheckboxSelectMultiple', 'MultiWidget', 'SplitDateTimeWidget', 
    2425) 
    2526 
     
    258259        return u'<ul>\n%s\n</ul>' % u'\n'.join([u'<li>%s</li>' % w for w in self]) 
    259260 
    260261class RadioSelect(Select): 
     262    field_renderer = RadioFieldRenderer 
     263 
     264    def __init__(self, *args, **kwargs): 
     265        field_renderer = kwargs.pop('field_renderer', None) 
     266        if field_renderer: 
     267            self.field_renderer = field_renderer 
     268        super(RadioSelect, self).__init__(*args, **kwargs) 
     269 
    261270    def render(self, name, value, attrs=None, choices=()): 
    262271        "Returns a RadioFieldRenderer instance rather than a Unicode string." 
    263272        if value is None: value = '' 
    264273        str_value = smart_unicode(value) # Normalize to string. 
    265274        final_attrs = self.build_attrs(attrs) 
    266         return RadioFieldRenderer(name, str_value, final_attrs, list(chain(self.choices, choices))) 
     275        return self.field_renderer(name, str_value, final_attrs, list(chain(self.choices, choices))) 
    267276 
    268277    def id_for_label(self, id_): 
    269278        # RadioSelect is represented by multiple <input type="radio"> fields, 
  • tests/regressiontests/forms/tests.py

     
    688688<li><label><input type="radio" id="bar_3" value="R" name="beatle" /> Ringo</label></li> 
    689689</ul> 
    690690 
     691# Override the field_renderer to change the output 
     692>>> class MyRenderer(RadioFieldRenderer): 
     693...    def __unicode__(self): 
     694...        return u',\n'.join([u'%s' % w for w in self]) 
     695>>> w = RadioSelect(field_renderer=MyRenderer) 
     696>>> print w.render('beatle', 'G', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))) 
     697<label><input type="radio" name="beatle" value="J" /> John</label>, 
     698<label><input type="radio" name="beatle" value="P" /> Paul</label>, 
     699<label><input checked="checked" type="radio" name="beatle" value="G" /> George</label>, 
     700<label><input type="radio" name="beatle" value="R" /> Ringo</label> 
     701 
    691702# CheckboxSelectMultiple Widget ############################################### 
    692703 
    693704>>> w = CheckboxSelectMultiple()