开发者

How to change Django NullBooleanField widget application wide?

I would want to display all NullBooleanFields in开发者_C百科 my application as radio buttons. What's the best way to do it?

Following template or something similar would be ideal. Just to allow rich styling and tone-of-voice different from plain "Yes/No/Unknown".

'''<li class="field-%s">
    <label class="%s" title="%s">%s</label>
    <label class="y"><input type="radio" name="%s" value="1" %s /> %s</label>
    <label class="n"><input type="radio" name="%s" value="0" %s /> %s</label>
    <label class="e"><input type="radio" name="%s" value=""  %s /> %s</label>
    </li>
''' % (
        field,
        field, help text, verbose_name,
        field, y, y_label,
        field, n, n_label,
        field, e, e_label
    )


In the end I figured that setting widgets to RadioSelect one by one was less code even though I have a lot of NullBooleanFields. The <ul> producted by RadioSelect widget is enough structure to style on, even though it requires CSS3 selectors.

Not DRY, but less hassle. One needs to be pragmatic and move on.

If someone could provide code to change the default widget for NullBooleanField from NullBooleanSelect to RadioSelect on the forms.py level, I'd happily accept the answer.


I just implemented a custom widget to do this:

class YesNoNARadioSelect(widgets.Widget):
    CHOICES=((True,'Yes'),(False,'No'),(None,'N/A'))

    def render(self,name,value,attrs=None):
        s=[]
        for c in self.CHOICES:
            extraAttrs=attrs.copy()
            extraAttrs.update(dict(type='radio',name=name,value=c[0]))
            if value==c[0]: extraAttrs['checked']='checked'
            extraAttrs=self.build_attrs(extraAttrs)
            s.append(format_html('<label><input {}/>{}</label>',flatatt(extraAttrs),c[1]))
        return S(''.join(s))

Seems to work for me, although I'd like to hear of anything that I'm doing wrong with it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜