在 Django 中使表单选择列表保持最新

Keeping form choice list up-to-date in django

我的管理站点中有一个表单,用户可以在其中从下拉列表中select来自特定模型的单个对象。

thing_choices = [(x.id, x) for x in Things.objects.all()]

class ThingSelector(forms.Form):
    thing = forms.ChoiceField(choices=thing_choices)

如果我先添加一个新的 Thing 对象,然后转到带有 selector 表单的页面,我发现该对象没有出现在下拉列表中。这大概是我第一次启动服务器时表格中填充的选项。测试证实了这一点,因为如果我重新启动 Django,新的选择就会出现在列表中。

我怎样才能解决这个问题,以便我可以创建对象并将它们也显示在此表单上?

(更多信息:selected 内容与表单一起提交,以便对其进行处理。)

谢谢...

If I first add a new Thing object, then go to the page with the selector form, I find that the object does not appear in the dropdown. This is presumably the form was populated with choices when I first stood the server up.

正确,变量 thing_choices 是在您的代码 first 运行 时计算的,如果它与您的表单在同一范围内,则不太可能曾经 运行 一次。

一种更简单的方法是使用引用模型的 ModelChoiceField,而不是 ChoiceField。像这样:

class ThingSelector(forms.Form):
    thing = forms.ModelChoiceField(queryset=Things.objects.all()

这应该意味着随着新的 Thing 个对象的添加,它们可以在表单中被选中。