Django:如何使用存储的模型实例作为表单选择?

时间:2023-01-14 19:37:14

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?

我有一个基本上只是一个字符串的模型(django.db.models.CharField)。只存储此模型的几个实例。我怎样才能将这些值用作表单中的选项?

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

为了说明,该模型可以是BlogTopic。我想让用户能够选择一个或多个主题进行订阅。

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.

但我不确定何时会定义选择。我假设只在首次导入模块时(即启动Django时)。显然这不是一个很好的方法。

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.

这似乎是一个常见的要求,但我似乎找不到任何例子。我怀疑我可能会遗漏一些明显的东西。无论如何,提前感谢您的答案。

1 个解决方案

#1


19  

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

#1


19  

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