Django将相同的类属性添加到所有相同的类型字段

时间:2011-05-26 15:19:58

标签: django attributes

有没有简单的方法可以将class=radio分配给窗体小部件在窗体中进行辐射选择的所有元素? 我知道我可以写这样的

rb = forms.ChoiceField( widget=forms.RadioSelect(attrs='class':'radio'))

表单中的所有单选按钮,但我认为应该有其他方式。因为我可能会将它用于所有单选按钮,所以写这个并不好玩。

2 个答案:

答案 0 :(得分:2)

您可以创建自己的小部件,如下所示:

class MyRadioSelect(forms.RadioSelect):

    def __init__(self, *args, **kwargs):
         attrs = kwargs.pop("attrs", {})
         if "class" in attrs:
             attrs["class"] = "%s radio" % attrs["class"]
         else:
             attrs["class"] = "radio"
         kwargs["attrs"] = attrs
         super(MyRadioSelect, self).__init__(*args, **kwargs)

答案 1 :(得分:1)

像这样?

class ClassyRadioSelect(forms.RadioSelect):
    def __init__(self, *args, **kwargs):
        #yes, i've to look up how to process args and kwargs properly
        attrs = kwargs.get('attrs', {})
        attrs['class'] = ' '.join((attrs.get('class',''), 'radio'))
        kwargs['attrs'] = attrs
        super(ClassyRadioSelect, self).__init__(*args, **kwargs)

class ClassyChoiceField(forms.ChoiceField):
    def __init__(self, choices=(), required=True, widget=None, label=None,
                 initial=None, help_text=None, *args, **kwargs):
        if not widget:
            widget = ClassyRadioSelect()
        super(ClassyChoiceField, self).__init__(choices, required, widget, label
                                                , initial, help_text, *args,
                                                **kwargs)

class MyForm(forms.Form):
    classy_field1 = ClassyChoiceField()
    classy_field2 = ClassyChoiceField()