【问题标题】:ModelChoiceField always raises : "Select a valid choice. That choice is not one of the available choices"ModelChoiceField 总是引发:“选择一个有效的选择。该选择不是可用的选择之一”
【发布时间】:2018-03-23 15:34:29
【问题描述】:

我有一个 ModelChoiceField,其中包含从我的数据库中选择的客户名称。 但是当我提交表单时:

“选择一个有效的选项。该选项不是可用选项之一”

这是我的表格:

class FormVents(forms.Form):
  client_name=forms.ModelChoiceField(queryset=client.objects.all().values_list('nom', flat=True),required=False)

  def clean(self):
     client_name = self.cleaned_data.get('client_name')
     print(client_name)

我尝试打印 client_name 以检查我是否可以获得该值,但我得到了 None !我想这就是为什么我总是得到那个错误 不知道是什么问题?我称呼该领域的方式不对吗? 请提供任何帮助。非常感谢

【问题讨论】:

    标签: django forms modelchoicefield


    【解决方案1】:

    删除.values_list('nom', flat=True)

    IE

    client_name=forms.ModelChoiceField(queryset=client.objects.all(), required=False)
    

    如果您希望 value 属性是模型中的特定字段(默认使用主键),请为模型选择字段使用 to_field_name 关键字。

    例如,

    client_name=forms.ModelChoiceField(queryset=client.objects.all(), to_field_name='nom', required=False)
    

    【讨论】:

    • 非常感谢,你真的帮了我很多。
    猜你喜欢
    • 1970-01-01
    • 2018-06-11
    • 2021-04-12
    • 2017-12-30
    • 2020-10-30
    • 2017-04-21
    • 1970-01-01
    • 2014-06-24
    • 2016-05-18
    相关资源
    最近更新 更多