Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django radioselect render to table

I want to render the django form widget radioselect into a table rather than a ul list. With labels in the first row and the radio buttons below in the second row. One cell for each button. e.g.

-------------------------------
| label 1 | label 2 | label 3 |
-------------------------------
|   O     |    O    |    O    |
-------------------------------

I've looked at the default selectradio widget but the render function seems so complicated, calling many different classes to do each part of the render.

Does anyone have any examples of how to do this or could provide a simple solution?

like image 620
John Avatar asked Dec 29 '22 01:12

John


2 Answers

Just to fill in a bit more of Béres Botond's answer

class MyForm(forms.ModelForm):
    my_field = forms.TypedChoiceField(choices=some_choices,
                                      label=u"bla",
                                      widget=forms.RadioSelect(renderer=MyCustomRenderer))

The custom renderer would look like:

from django import forms
from django.forms.widgets import RadioFieldRenderer
from django.utils.encoding import force_unicode
from django.utils.safestring import mark_safe

class MyCustomRenderer( RadioFieldRenderer ):
    def render( self ):
        """Outputs a series of <td></td> fields for this set of radio fields."""
        return( mark_safe( u''.join( [ u'<td>%s</td>' % force_unicode(w.tag()) for w in self ] )))

In this case I didn't want the name of the radio box next to it, so I am using "force_unicode(w.tag())" If you wanted the name next to it, just render the object directly like "force_unicode(w)"

I hope that helps!

like image 130
albrnick Avatar answered Jan 11 '23 20:01

albrnick


You need to subclass django.forms.widgets.RadioFieldRenderer and override it's render method. Then in your form, when declaring your field specify the custom renderer for the widget

class MyForm(forms.ModelForm):
    my_field = forms.TypedChoiceField(choices=some_choices,
                                      label=u"bla",
                                      widget=forms.RadioSelect(renderer=MyCustomRenderer))
like image 27
Botond Béres Avatar answered Jan 11 '23 20:01

Botond Béres