Django widget renderer render
I got a little frustrated trying to find the ‘simple’ answer to change the html which is generated by the various form field widgets.
In this case the RadioSelect field generates radio buttons wrapped in an unordered list. It was annoying, and whilst I could resort to writing the html directly in the html; that’s not ideal.
The solution is not hard, just not well documented.
We need only write a “render” routine to return the string we want. Then override the default widget with our renderer, and finally specify all that in the form field definition:
from django import forms
from django.forms import ModelForm
from django.utils.safestring import mark_safe
from django.utils.encoding import force_unicode
FULFILMENT_CHOICES = (
('Post','Post'),
('Pickup','Pickup')
)
class MyRadioRenderer(forms.widgets.RadioFieldRenderer): """Render radio buttons without the <li>"""
def render(self):
return mark_safe(u'\n%s\n' % u'\n'.join([u'%s'
% force_unicode(w) for w in self]))
class OrderForm(ModelForm):
fulfilment = forms.ChoiceField(
widget=forms.RadioSelect(renderer=MyRadioRenderer),
choices=FULFILMENT_CHOICES)
Produces:
<div class="orderValue"> <label for="id_fulfilment_0"><input type="radio" id="id_fulfilment_0" value="Post" name="fulfilment"/> Post</label> <label for="id_fulfilment_1"><input type="radio" id="id_fulfilment_1" value="Pickup" name="fulfilment"/> Pickup</label> </div>
John is a freelance programmer living in Sydney Australia. He blogs whatever takes his fancy; computing tips, travel letters, and random stuff from his life. He does it primarily to learn and demonstrate the running of a website.
Recent Comments