你如何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)
我试图在这里提出的解决方案:
堆栈溢出Q -设置CHOICES = [('','All')] + CHOICES
导致了一个内部服务器错误。
堆栈溢出Q2 -确定后('', '---------'),
在我的选择,还是默认的第一个项目在列表中,而不是('', '---------'),
选择。
吉斯特 -尝试使用EmptyChoiceField
这里定义,但使用Django 1.4没有工作。
但这些都没有工作对我来说..你将如何解决这个问题? 感谢您的想法!
Answer 1:
查看Django的1.11文档ChoiceField 。 对于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)
请注意,您可以避开形式的错误,如果你想在表单字段是通过使用可选的“需要=假”
另外,如果你已经有了一个CHOICE_LIST没有empty_value,你可以插入一个,这样它首先显示出来的形式下拉菜单:
CHOICE_LIST.insert(0, ('', '----'))
Answer 2:
下面是我使用的解决方案:
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();'}))
Answer 3:
你可以试试这个(假设你的选择是元组):
blank_choice = (('', '---------'),)
...
color = forms.ChoiceField(choices=blank_choice + COLORS)
year = forms.ChoiceField(choices=blank_choice + YEAR_CHOICES)
另外,我无法从你的代码,这是否是一个形式或的ModelForm告诉我们,但它是后者,没有必要在这里重新定义表单字段(可以直接包括选择=颜色,选择= YEAR_CHOICES模型场。
希望这可以帮助。
Answer 4:
我知道你已经接受一个答案,但我只是想万一有人张贴了这一点,有跑进我有,即接受的解决方案不以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")
Answer 5:
曾在模型中使用0,而不是U“”,因为整场的。 (错误是对于int()与底座10无效字面:“)
如果存在的话前面加上一个空的标签(而不是必填字段!)
if not required and empty_label is not None:
choices = tuple([(0, empty_label)] + list(choices))
Answer 6:
有点迟到了..
如何不修改所有的选择,只是一个小部件的处理呢?
from django.db.models import BLANK_CHOICE_DASH
class EmptySelect(Select):
empty_value = BLANK_CHOICE_DASH[0]
empty_label = BLANK_CHOICE_DASH[1]
@property
def choices(self):
yield (self.empty_value, self.empty_label,)
for choice in self._choices:
yield choice
@choices.setter
def choices(self, val):
self._choices = val
然后,只需调用它:
class SomeForm(forms.Form):
# thing = forms.ModelChoiceField(queryset=Thing.objects.all(), empty_label='Label')
color = forms.ChoiceField(choices=COLORS, widget=EmptySelect)
year = forms.ChoiceField(choices=YEAR_CHOICES, widget=EmptySelect)
当然, EmptySelect
将被置于某种内部common/widgets.py
代码,然后当过你需要它,只是引用它。
Answer 7:
它是不一样的形式,但我做到了由EmptyChoiceField方法的启发方式如下:
from django import forms
from ..models import Operator
def parent_operators():
choices = Operator.objects.get_parent_operators().values_list('pk', 'name')
choices = tuple([(u'', 'Is main Operator')] + list(choices))
return choices
class OperatorForm(forms.ModelForm):
class Meta:
model = Operator
# fields = '__all__'
fields = ('name', 'abbr', 'parent', 'om_customer_id', 'om_customer_name', 'email', 'status')
def __init__(self, *args, **kwargs):
super(OperatorForm, self).__init__(*args, **kwargs)
self.fields['name'].widget.attrs.update({'class': 'form-control m-input form-control-sm'})
self.fields['abbr'].widget.attrs.update({'class': 'form-control m-input form-control-sm'})
self.fields['parent'].widget.attrs.update({'class': 'form-control m-input form-control-sm'})
self.fields['parent'].choices = parent_operators()
self.fields['parent'].required = False
self.fields['om_customer_id'].widget.attrs.update({'class': 'form-control m-input form-control-sm'})
self.fields['om_customer_name'].widget.attrs.update({'class': 'form-control m-input form-control-sm'})
self.fields['email'].widget.attrs.update({'class': 'form-control m-input form-control-sm', 'type': 'email'})enter code here
文章来源: Empty Label ChoiceField Django