Forms - Widget - Radioselect - how to set initial value on a static form

4,311 views
Skip to first unread message

Roboto

unread,
Jun 22, 2010, 9:46:51 PM6/22/10
to Django users
I can't seem to find documentation on this anywhere, so I imagine
someone must have run into this.

if I had a radioselect Yes / No and I wanted the default value to be
'No', but I'm not loading this data from a database or anything, is
there a method to just insert an initial value so that the html comes
out as <option selected = True>No</option>

?

Any ideas? This is so basic it's killing me.

Karen Tracey

unread,
Jun 22, 2010, 11:37:51 PM6/22/10
to django...@googlegroups.com

You say RadioSelect widget but you mention HTML that doesn't go with a radio input type -- option goes with a <SELECT ...> construct? If you showed some code for what you are trying it might help people help you. The way to specify the initially-selection option for a RadioSelect is to specify it as the initial value for the associated form field. For example:

class F1(forms.Form):
    rs_field = forms.ChoiceField(choices=(('Y','Yes'), ('N','No')),
        initial='N', widget=forms.RadioSelect)

which would render (unbound) as:

<tr><th><label for="id_rs_field_0">Rs field:</label></th><td><ul>
<li><label for="id_rs_field_0"><input type="radio" id="id_rs_field_0" value="Y" name="rs_field" /> Yes</label></li>
<li><label for="id_rs_field_1"><input checked="checked" type="radio" id="id_rs_field_1" value="N" name="rs_field" /> No<
/label></li>
</ul></td></tr>

...with the "No" radio input initially selected, since it specified the checked attribute.

Karen
--
http://tracey.org/kmt/

euan.g...@gmail.com

unread,
Jun 23, 2010, 4:12:47 AM6/23/10
to Django users
Karen's suggestion is great. You can also pass initial data into the
form constructor. So using the example above if you do (in your view):

my_form = F1(initial=dict(rs_field='N'))

you'll achieve the same result. Don't think there's much to be said
for either way other the way I just suggest might allow you a bit more
flexibility if you want something in the view to dictate the initial
value.

Euan

On Jun 23, 4:37 am, Karen Tracey <kmtra...@gmail.com> wrote:
Reply all
Reply to author
Forward
0 new messages