Tutorial :Django: How to use stored model instances as form choices?



Question:

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.


Solution:1

topics = forms.ModelMultipleChoiceField(queryset=BlogTopic.objects.all())  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »