django表单下拉字段中的占位符 [英] Placeholder in django form dropdown field
问题描述
我对Django形式的下拉字段有一点疑问。我想在此字段中添加占位符(或不使用活动的第一选项作为占位符),并添加一些其他内容,例如不添加标签,类等。
我在 forms.py
,但现在我的表单已损坏-不要将值保存到数据库。
I have a little problem with a dropdown field in django form. I want to add to this field placeholder (or not active first option as placeholder) and some other stuff as no label, class etc.
I wrote something like this, in my forms.py
but now my form is broken - don't save values to database.
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']
其他所有字段类型都可以使用,但是此下拉列表不起作用...
您能帮我吗?
Every other field type is working, but not this dropdown... Could you help me?
推荐答案
默认情况下,ModelChoiceField使用的窗口小部件的顶部会有
空选择清单。您可以使用empty_label
属性更改此
标签的文本(默认情况下为 ---------),也可以通过设置$ b完全禁用空标签$ b empty_label设置为None:
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
设置为无
,此选项未显示。
As you're setting empty_label
to None
, this option is not being shown.
示例
scenario_area = forms.ModelChoiceField(label="", queryset=ScenarioArea.objects.distinct('scenarioAreaName'), empty_label="Placeholder")
这篇关于django表单下拉字段中的占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!