views:

236

answers:

2

I have a form like this:

CHOICES = [  
           ('a', 'a_value'),  
           ('b', 'b_value'),  
           ('c', 'c_value')  
]  

self.fields["choice"] = forms.ChoiceField(  
    widget=RadioSelect(),  
    choices=CHOICES,   
)  

How can I select a single element of this form field in my template? I want to be able to do something like:

<tr><td>{{form.choice.a}}</td><td>some custom extra field</td></tr>

Or is there another way to change how the RadioSelect is rendered?

A: 

You cannot do this via parameters or something, the way it is rendered is hardcoded in its widget class! See eg. http://code.djangoproject.com/browser/django/trunk/django/forms/widgets.py: RadioSelect.render (->RadioFieldRenderer.render); subclass it and override the render method, then use it in your form myfield = forms.MultipleChoiceField(widget=MyWidget(...)).

lazerscience
Just one more thing..is there a way to pass arguments to my subclassed renderer? When I try to pass arguments now, it says the object is not callable..
Oli
What do you want to pass?
lazerscience
A: 

I labored over this for a few hours trying to find some way to use a custom renderer on a RadioSelect, but there is no way to pass in the choice number. Instead I went for a kludgey, but simple approach. In added an __init__ function to my form:

def __init__(self, *args, **kwargs):
    super(FormName, self).__init__(*args, **kwargs)
    self.radiofield_choice = re.findall(r'<li>(.+?)</li>',
                                        unicode(self['radiofield_name']))

That uses the RadioSelect's default render to create the widget, and then parses out the individual choice HTML. You could even combine that with the defined choices to create a dictionary instead of a list.

In my template I used {{ form.radiofield_choice.0|safe }} to render just the first item. Increment the zero to get the other items.

Dave