如何在Django中使用ModelChoiceField(queryset = ...)从选项中获取所选值

时间:2019-07-06 07:46:00

标签: django

class Model_Neural_form(forms.ModelForm):
    allMod = forms.ModelChoiceField(queryset=Model_Neural.objects.all())

    class Meta:
        model = Model_Neural
        fields = ["nom_mod", "modl"]

    def __init__(self, *args, **kwargs):
        super(Model_Neural_form, self).__init__(*args, **kwargs)
        self.fields['allMod'].label = ''

1 个答案:

答案 0 :(得分:0)

如果要设置默认初始值,则应像其他表单字段一样定义初始值。

创建表单时,您需要设置初始名称:

allMod = forms.ModelChoiceField(
    initial=instance.pk if instance else None,
    queryset=Model_Neural.objects.all()
)