将收音机转换为 Select

Convert a Radio to a Select

我自己做了这样的 FieldRenderer:

class BootstrapRadioFieldRenderer(ChoiceFieldRenderer):
    outer_html = '<span {id_attr}>{content}</span>'
    inner_html = '<div class="radio">{choice_value}{sub_widgets}</div>'
    choice_input_class = RadioChoiceInput


class BootstrapRadioSelect(RendererMixin, Select):
    renderer = BootstrapRadioFieldRenderer
    _empty_value = ''

如您所见,它基于输出 Radio 元素的 RadioChoiceInput。我想将其更改为输出一个简单的 "Select" 元素。如何做到这一点?

(当然,我尝试将 RadioChoiceInput 更改为 Select,我得到 __init__() takes at most 3 arguments (6 given)

ChoiceFieldRenderer 意味着

An object used by RadioSelect to enable customization of radio widgets.

但是,它似乎对自定义 Select 小部件没有用。

为此,我建议您继承 the Select widget and override it's render method, as described in docs

或者,如果您真的想要,您可以定义自己的 SelectRenderer,它会依次遍历小部件的 self.choices 并按照您的意愿呈现它们。

如果您在定义小部件的其他子类(仅修改渲染)时需要更大的灵活性,这将很有用;我可以想象其他 Django 用户也会从这种通用 "rendering customization" 中受益,因此请随时在 the django-developers mailing list.

中讨论此功能

我不知道我怎么了...因为答案很简单。

我不必触摸我的模型。在我所有的表格中,我都有这样的东西:

a = _(u'Statut:')
statut = forms.TypedChoiceField(
    label=a, required=False,
    choices=[(k, Personne.TAB_STATUT[k])
             for k in Personne.TAB_STATUT],
    widget=BootstrapRadioSelect(attrs={
        'title': a,
    }),
    error_messages=e)

我只需要更改它们:"back to classical":

statut = forms.CharField(
    label=a, required=False,
    widget=forms.Select(attrs={
        'title': a,
        'class': 'form-control'},
        choices=[(k, Personne.TAB_STATUT[k])
                 for k in Personne.TAB_STATUT],),
    error_messages=e)

而且效果非常好。