views:

178

answers:

1

I have a model which is essentially just a string (django.db.models.CharField). There will only be several instances of this model stored. How could I use those values as choices in a form?

To illustrate, the model could be BlogTopic. I'd like to offer users the ability to choose one or several topics to subscribe to.

I started writing something like:

from mysite.blog.models import BlogTopic

choices = [(topic.id, topic.name) for topic in BlogTopic.objects.all()]

class SubscribeForm(forms.Form):
    topics = forms.ChoiceField(choices=choices)

But I'm not sure when choices would be defined. I assume only when the module is first imported (i.e. when starting Django). Obviously that is not a very good approach.

This seems like it would be a common requirement, but I can't seem to find any examples. I suspect I may be missing something obvious here. Anyway, thanks in advance for your answers.

+5  A: 
topics = forms.ModelMultipleChoiceField(queryset=BlogTopic.objects.all())
zalew
Good answer, except not sure why you use ModelMultipleChoiceField - given the OP use of ChoiceField, the appropriate equivalent would be just ModelChoiceField.
Carl Meyer