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.
The __str__ method just tells Django what to print when it needs to print out an instance of the any model.
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 ).
topics = forms.ModelMultipleChoiceField(queryset=BlogTopic.objects.all())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With