【问题标题】:how to delete the ---- generated by select choices如何删除选择选择生成的----
【发布时间】: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


【解决方案1】:

models.CharField 在有选项时默认使用TypedChoiceField 表单域。因此无需手动指定它(也是它的django.forms.fields.TypedChoiceField)。

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

>>> 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-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    • 1970-01-01
    相关资源
    最近更新 更多