2012-10-12 28 views
1

我有一個問題,我如何擺脫----從選擇下拉菜單不顯示空(---)在第一個行。我從RadioSelect計算器發現我設法擺脫了---但我被困在選擇下拉菜單... :( 這裏是我的編碼例。如何刪除----生成的選擇選項

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顯示爲下拉菜單,也沒有顯示----第一排。但如果使用類似上面的代碼IM,我得到COLORSELECTRadioSelect並沒有顯示----(whi ch是我想要的不顯示---)但不是RadioSelect

非常感謝你提前。

+1

這個什麼:http://stackoverflow.com/questions/8220404/django-how-to-exclude-the-bogus-option-from-select-element-generated-fro – danihp

+0

您是否嘗試過刪除blank =從模型定義中爲真? – qdot

+0

嗨,感謝您的快速回復。我做了嘗試,但我得到一個錯誤「'模塊'對象沒有屬性'TypedChoiceField'」。那什麼意識? – noobes

回答

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>