django 表单下拉字段中的占位符

Placeholder in django form dropdown field

我对 django 形式的下拉字段有点问题。我想添加到这个字段占位符(或作为占位符不活跃的第一个选项)和其他一些东西,如无标签,class 等。 我在我的 forms.py 中写了这样的东西,但现在我的表格坏了 - 不要将值保存到数据库。

from .models import Scenario, ScenarioArea
from django import forms

class newScenario(forms.ModelForm):
    scenarioArea=forms.ModelChoiceField(label="", queryset=ScenarioArea.objects.values_list("scenarioAreaName", flat=True).distinct(), empty_label=None)

lass Meta:
        model = Scenario
        fields = ['scenarioArea']

所有其他字段类型均有效,但此下拉列表无效... 你能帮帮我吗?

By default the widget used by ModelChoiceField will have an empty choice at the top of the list. You can change the text of this label (which is "---------" by default) with the empty_label attribute, or you can disable the empty label entirely by setting empty_label to None:

当您将 empty_label 设置为 None 时,此选项未显示。

例子

scenario_area = forms.ModelChoiceField(label="", queryset=ScenarioArea.objects.distinct('scenarioAreaName'), empty_label="Placeholder")