从数据库填充 ChoiceField

Ste*_*en 5 python django django-forms

我希望我的表单中有几个字段被呈现为 ChoiceFields,它们从数据库中获取它们的内容。

我在想这样的事情:

class SeriesForm(ModelForm):
  series = forms.ChoiceField(choices=Series.objects.all())

  class Meta:
    model = Series
    exclude = ('model', 'date_added',)
Run Code Online (Sandbox Code Playgroud)

但是该字段series现在根本没有出现在我的表单中。我错过了什么?

在尝试解决方案(使用ModelChoiceField)后,我仍然看到同样的问题。这是我的代码:

series = forms.ModelChoiceField(queryset=Series.objects.values('series'), 
  empty_label="     ")
Run Code Online (Sandbox Code Playgroud)

Ign*_*ams 5

使用 aModelChoiceField代替。

  • @Ignacio 如果您在答案中实际解决了用户的问题,而不是链接到可以移动或更改 URL 的站点,从而使您的答案变得毫无用处,这对用户更有帮助。 (5认同)