【发布时间】:2012-10-12 00:03:10
【问题描述】:
我有一个问题,关于如何从选择下拉菜单中去掉 ---- 而不在第一行显示 null(---)。我从 RadioSelect 上的 stackoverflow 中找到,我设法摆脱了 --- 但我被困在选择下拉菜单中......:( 这是我的编码示例。
models.py
colorradio = (("1" , 'Yellow'),
("2" , 'Red'),
("3" , 'Blue'),
("4" , 'Black'),)
COLORRADIO = models.CharField(max_length = 2, choices = colorradio, null = True, blank = True)
colorselect= (("1" , 'Yellow'),
("2" , 'Red'),
("3" , 'Blue'),
("4" , 'Black'),)
COLORSELECT= models.CharField(max_length = 2, choices = colorselect, null = True, blank = True)
forms.py
class RadioSelectNotNull(RadioSelect, Select):
def get_renderer(self, name, value, attrs=None, choices=()):
"""Returns an instance of the renderer."""
if value is None: value = ''
str_value = force_unicode(value) # Normalize to string.
final_attrs = self.build_attrs(attrs)
choices = list(chain(self.choices, choices))
if choices[0][0] == '':
choices.pop(0)
return self.renderer(name, str_value, final_attrs, choices)
class RainbowForm(ModelForm):
class Meta:
model = Rainbow
widgets = {'COLORRADIO':RadioSelectNotNull(), # this is correct and NOT shown ---
'COLORSELECT':RadioSelectNotNull(), #should be in dropdown menu
}
我确实喜欢将COLORSELECT 显示为下拉菜单,并且也没有在第一行显示----。但是,如果我使用上面的代码,我会得到COLORSELECT 作为RadioSelect 并且不显示----(这是我想要的不显示---)但不是RadioSelect。
非常感谢您。
【问题讨论】:
-
您是否尝试过从模型定义中删除 blank=True?
-
您好,感谢您的快速回复。我确实尝试过,但我得到一个错误“'模块'对象没有属性'TypedChoiceField'”。这是什么意思?
-
嗨,qdot。是的,我做到了,但没有运气..我也让它空白=False,默认=0和默认=1,但没有运气..:(
-
得到了答案....感谢@danihp :)
标签: django django-forms django-widget