如何在Django中选择可选字段?

时间:2022-10-17 19:56:46

I am making Django form with an optional select box. I have made a list of tuples per the documentation and have created this field:

我正在用一个可选的选择框创建Django表单。我根据文档列出了一个元组列表,并创建了这个字段:

MY_CHOICES = [('a', 'a'), ('b', 'b'), ('c', 'c')]
selections = forms.ChoiceField(choices=MY_CHOICES, required=False)

However, the resulting select box does not have an option akin to "----" or "leave blank." It merely lists all of the choices even if I specify required=False.

但是,结果的选择框没有类似于“——”或“留空”的选项。它仅仅列出所有的选项,即使我指定required=False。

How can I make this select box optional? Should I just add ('', '----') as the first tuple in my list? Thank you.

如何使这个选择框可选?我是否应该将(",'--- ')作为列表中的第一个元组?谢谢你!

1 个解决方案

#1


1  

As you're not using a ModelChoiceField, you are explicitly stating the choices you want. You would need to add an empty choice as the first tuple to show an "empty" choice.

当您没有使用ModelChoiceField时,您将显式地声明您想要的选择。您需要添加一个空选项作为第一个显示“空”选项的元组。

#1


1  

As you're not using a ModelChoiceField, you are explicitly stating the choices you want. You would need to add an empty choice as the first tuple to show an "empty" choice.

当您没有使用ModelChoiceField时,您将显式地声明您想要的选择。您需要添加一个空选项作为第一个显示“空”选项的元组。