Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 213
Chris Lawlor Avatar asked Apr 14 '09 19:04

Chris Lawlor


People also ask

What is __ str __ in Django?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model.

What is the difference between form and ModelForm in Django?

The differences are that ModelForm gets its field definition from a specified model class, and also has methods that deal with saving of the underlying model to the database. Show activity on this post. Show activity on this post. Form is a common form that is unrelated to your database (model ).


Video Answer


1 Answers

topics = forms.ModelMultipleChoiceField(queryset=BlogTopic.objects.all())
like image 58
zalew Avatar answered Sep 30 '22 07:09

zalew