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>
This entry was posted in geek and tagged . Bookmark the permalink.

One Response to Django widget renderer render

  1. Jul says:

    Thanks! It saved my day!

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>