1

我有一个问题,关于如何从选择下拉菜单中删除 ---- 不在第一行显示 null(---)。我从 RadioSelect 上的 stackoverflow 中发现,我设法摆脱了 --- 但我被困在选择下拉菜单中......:(这是我的编码示例。

模型.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)

表格.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显示为下拉菜单,也没有在第一行显示----。但是,如果我使用上面的代码,我会得到COLORSELECTasRadioSelect而不是显示 ---- (这是我想要的不显示 ---)但不是 as RadioSelect

非常感谢你。

4

1 回答 1

1

models.CharFieldTypedChoiceField默认情况下,当有选择时使用表单字段。因此无需手动指定它(也是它的django.forms.fields.TypedChoiceField)。

尝试删除blank=True并设置默认值(或在 中提供初始值formfield,通常您不必这样做,ModelForm会为您处理它)。CharField具有可空性也没有意义;我正在按照惯例切换变量COLORSELECT名称colorselect

>>> COLORSELECT = (("1" , 'Yellow'),
...               ("2" , 'Red'),
...               ("3" , 'Blue'),
...               ("4" , 'Black'),)

>>> colorselect = models.CharField(max_length=2, choices=COLORSELECT, default='1')
>>> colorselect.formfield().__class__
django.forms.fields.TypedChoiceField

>>> print(colorselect.formfield().widget.render('','1'))
<select name="">
<option value="1" selected="selected">Yellow</option>
<option value="2">Red</option>
<option value="3">Blue</option>
<option value="4">Black</option>
</select>
于 2012-10-12T05:39:47.487 回答