Reputation: 24981
Suppose I created a django form that has a radio box selection in it:
class PlaylistsForm(forms.Form):
choices=forms.ChoiceField( widget=forms.RadioSelect(), CHOICES,label="choices")
If I try to instantiate the form and do form.choices
I get an error that the instance has no attribute choices
. Can you refer me to somewhere where it explains the magic behind the creation of the fields, and secondly, how can I access the fields?
EDIT:
To make it clear: I want to know why, given an instance of PlaylistsForm
, doing
print form.choices
I get an error saying there's no such attribute. What dark magic is happening behind the scenes here?
Upvotes: 0
Views: 637
Reputation: 99751
Presuming CHOICES
is a tuple of options for the field, the change is relatively simple:
class PlaylistsForm(forms.Form):
choices=forms.ChoiceField(widget=forms.RadioSelect(),
choices=CHOICES,
label="choices")
See the documentation of ChoiceField
, and the documentation of choices
for more detail.
You're probably confusing your field called choices
, and the attribute choices
on your choices
field.
Say you've got a form:
my_form = PlaylistsForm()
You could access the choices
attribute of the choices
field like this:
my_form.fields['choices'].choices
I didn't know how to do what you wanted, so I stuck a import pdb; pdb.set_trace()
just after I declared a form, like this:
form = PlaylistsForm()
import pdb; pdb.set_trace()
Then, using the development server, I opened up a URL which mapped to the view with my new import pdb; pdb.set_trace()
in it. Switching over to my command prompt, I could inspect what attributes and methods existed on my form object at the debug prompt:
(Pdb) dir(form)
This showed me form
had a fields
attribute, so I looked at it:
(Pdb) form.fields
This showed me form.fields
is a dict
, with values being Field
objects, I picked out the choices
field, and looked to see what attributes it had:
(Pdb) dir(form.fields['choices'])
This showed me that form.fields['choices']
had a choices
attribute:
(Pdb) form.fields['chiices'].choices
[('', '---------'), (1L, My Playlist')]
This is probably what you're looking for.
Upvotes: 5