Re: Newbie question on forms using ChoiceField and "choices" field...
On Thu, Dec 15, 2011 at 8:27 PM, J. Marc Edwards
<marc.edwards@nimbisservices.com> wrote:
> OK...I have the following model and form.
>
> class CmdString(models.Model):
>
> name = models.CharField(max_length=50)
> cmd = models.CharField(max_length=200)
> eda_app = models.OneToOneField(EDA_App, primary_key=True)
>
> def __unicode__(self):
> return self.cmd
>
>
> class EDA_AppSelectForm(forms.Form):
> app_cmds = forms.ChoiceField(choices=CmdString.objects.all())
>
> Now the documentation for the "choices" kwarg is pasted below, which says
> that this should be an iterable of 2-tuples, but seems to indicate it could
> be a list as well. The documentation here seems unclear, i.e an iterable of
> tuple of 2-tuples, I don't think it means this.
>
> How can I achieve what I am looking for here?
choices needs to be an iterable of 2-tuples of strings, the first
being the value and the second the label. You are giving it a queryset
which will evaluate to a list of models.
Something like this would work:
class EDA_AppSelectForm(forms.Form):
app_cmds = forms.ChoiceField(choices=CmdString.objects.all().values_list('id',
'cmd'))
However, since you are dealing in models, you probably want to use a
proper form field, as this way, when you process the form again the
data in form.cleaned_data['app_cmds'] will be an id number of the
model chosen. It is better to get Django to do the work for you:
class EDA_AppSelectForm(forms.Form):
app_cmds = forms.ModelChoiceField(queryset=CmdString.objects.all())
Cheers
Tom
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home