1

最初の行に 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)

フォーム.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と NOT が表示されます ---- (これは、表示されないようにしたいものです ---) しかし、 as ではありませんRadioSelect

よろしくお願いします。

4

1 に答える 1

1

models.CharFieldTypedChoiceFieldデフォルトでは、選択肢がある場合はフォーム フィールドを使用します。したがって、手動で指定する必要はありません (また、そのdjango.forms.fields.TypedChoiceField)。

デフォルト値を削除blank=Trueして設定してみてください(または で初期値を指定するとformfield、通常はこれを行う必要はありませんModelForm。処理されます)。CharFieldまた、 nullableを持つことは意味がありません。慣例により、変数名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 に答える