空标签ChoiceField Django

Nic*_*k B 37 forms django label

你如何使ChoiceField标签表现得像ModelChoiceField?有没有办法设置empty_label,或至少显示一个空白字段?

Forms.py:

    thing = forms.ModelChoiceField(queryset=Thing.objects.all(), empty_label='Label')
    color = forms.ChoiceField(choices=COLORS)
    year = forms.ChoiceField(choices=YEAR_CHOICES)
Run Code Online (Sandbox Code Playgroud)

我试过这里建议的解决方案:

堆栈溢出Q - 设置CHOICES = [('','All')] + CHOICES导致内部服务器错误.

Stack Overflow Q2 - ('', '---------'),在我的选择中定义后,仍然默认为列表中的第一项,而不是('', '---------'),选项.

Gist - 尝试使用EmptyChoiceField此处定义,但使用Django 1.4无效.

但这些都不适合我..你怎么解决这个问题?谢谢你的想法!

Fiv*_*ver 42

请参阅ChoiceField上的Django 1.11文档.ChoiceField的'empty_value'被定义为空字符串'',因此您的元组列表应包含一个''映射到您想要为空值显示的值的键.

### forms.py
from django.forms import Form, ChoiceField

CHOICE_LIST = [
    ('', '----'), # replace the value '----' with whatever you want, it won't matter
    (1, 'Rock'),
    (2, 'Hard Place')
]

class SomeForm (Form):

    some_choice = ChoiceField(choices=CHOICE_LIST, required=False)
Run Code Online (Sandbox Code Playgroud)

请注意,如果您希望使用"required = False"将表单字段设置为可选,则可以避免表单错误

此外,如果您已经有一个没有empty_value的CHOICE_LIST,您可以插入一个,使其首先显示在表单下拉菜单中:

CHOICE_LIST.insert(0, ('', '----'))
Run Code Online (Sandbox Code Playgroud)


Nic*_*k B 16

这是我使用的解决方案:

from myapp.models import COLORS

COLORS_EMPTY = [('','---------')] + COLORS

class ColorBrowseForm(forms.Form):
    color = forms.ChoiceField(choices=COLORS_EMPTY, required=False, widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))
Run Code Online (Sandbox Code Playgroud)

  • 如果COLORS是一个元组,则不能向其添加列表。如果您将COLORS声明为元组的元组,则最好的方法是reczy所说的。blank_choice =(('','---------'),)blank_choice +颜色 (2认同)

VT_*_*rew 6

我知道您已经接受了答案,但我只想发布此内容,以防有人遇到我遇到的问题,即接受的解决方案不适用于 ValueListQuerySet。您链接到的EmptyChoiceField非常适合我(尽管我使用的是 django 1.7)

class EmptyChoiceField(forms.ChoiceField):
    def __init__(self, choices=(), empty_label=None, required=True, widget=None, label=None, initial=None, help_text=None, *args, **kwargs):

        # prepend an empty label if it exists (and field is not required!)
        if not required and empty_label is not None:
            choices = tuple([(u'', empty_label)] + list(choices))

        super(EmptyChoiceField, self).__init__(choices=choices, required=required, widget=widget, label=label, initial=initial, help_text=help_text, *args, **kwargs) 

class FilterForm(forms.ModelForm):
    #place your other fields here 
    state = EmptyChoiceField(choices=People.objects.all().values_list("state", "state").distinct(), required=False, empty_label="Show All")
Run Code Online (Sandbox Code Playgroud)


rec*_*czy 5

你可以试试这个(假设你的选择是元组):

blank_choice = (('', '---------'),)
...
color = forms.ChoiceField(choices=blank_choice + COLORS)
year = forms.ChoiceField(choices=blank_choice + YEAR_CHOICES)
Run Code Online (Sandbox Code Playgroud)

另外,我无法从您的代码中判断这是表单还是 ModelForm,但它是后者,无需在此处重新定义表单字段(您可以直接在模型字段中包含 options=COLORS 和 choice=YEAR_CHOICES .

希望这可以帮助。