空标签ChoiceField Django [英] Empty Label ChoiceField Django
问题描述
如何使 ChoiceField
的标签的行为像 ModelChoiceField
?有没有办法设置一个 empty_label
,或至少显示一个空白字段?
How do you make ChoiceField
's label behave like ModelChoiceField
? Is there a way to set an empty_label
, or at least show a blank field?
Forms.py:
thing = forms.ModelChoiceField(queryset=Thing.objects.all(), empty_label='Label')
color = forms.ChoiceField(choices=COLORS)
year = forms.ChoiceField(choices=YEAR_CHOICES)
< hr>
我已经尝试了这里提出的解决方案:
I have tried the solutions suggested here:
堆栈溢出问题 - 设置 CHOICES = [ ('','All')] + CHOICES
导致内部服务器错误。
Stack Overflow Q - Setting CHOICES = [('','All')] + CHOICES
resulted in an internal server error.
- 定义('','---------')后, ,
在我的选择中,仍然默认为列表中的第一个项目,而不是('','---------'),
c hoice。
Stack Overflow Q2 - After defining ('', '---------'),
in my choices, still defaulted to the first item in the list, not the ('', '---------'),
choice.
Gist - 尝试使用 EmptyChoiceField
在这里定义,但没有使用Django 1.4。
Gist - Tried using EmptyChoiceField
defined here, but did not work using Django 1.4.
但这些都没有为我工作..你会怎么样解决这个问题?感谢您的想法!
But none of these have worked for me.. How would you solve this issue? Thanks for your ideas!
推荐答案
以下是我使用的解决方案:
Here's the solution that I used:
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();'}))
这篇关于空标签ChoiceField Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!