如何将属性添加到django表单小部件的所有实例?

时间:2015-07-28 19:46:33

标签: django django-forms

所以我使用bootstrap构建Django表单,我知道我可以使用以下命令添加表单的属性(例如类):

username = forms.CharField(max_length=24, widget=forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Your desired username.'}))

但我无法找到任何方法将类属性应用于所有TextInput(或任何其他窗口小部件类)。 This对我没有帮助,因为它看起来只允许您设置整个样式表而不仅仅是属性。

我不想违反DRY,那么如何将某个属性应用于所有TextInput(或其他小部件)实例?

2 个答案:

答案 0 :(得分:1)

只需创建自己的CharField即可实现自己的widget_attrs方法:

原文:

class CharField(Field, forms.CharField):
    widget = TextInput

    def widget_attrs(self, widget):
        attrs = super(CharField, self).widget_attrs(widget)
        if attrs is None:
            attrs = {}
        if self.max_length is not None and isinstance(widget, (TextInput, HiddenInput)):
            # The HTML attribute is maxlength, not max_length.
            attrs.update({'maxlength': str(self.max_length)})
        return attrs

建议:

class MyCharField(forms.CharField):
    def widget_attrs(self, widget):
        attrs = super(MyCharField, self).widget_attrs(widget)
        attrs.update({'class':'form-control', 'placeholder': 'Your desired username.'})
        if self.max_length is not None and isinstance(widget, (forms.TextInput, forms.HiddenInput)):
            # The HTML attribute is maxlength, not max_length.
            attrs.update({'maxlength': str(self.max_length)})
        return attrs

如果你总是指定一个max_length,你可能也会遗漏if-clause,但是你可以试试。

答案 1 :(得分:0)

简单的方法:

def set_attrs_for_fields(fields, default_attrs):
    for field_name in fields:
        field = fields[field_name]
        try:
            default_widget_attr = default_attrs[field.widget.__class__]
            for k, v in default_widget_attr.items():
                field.widget.attrs[k] = v
        except KeyError:
            pass

class MyForm(ProjFormBase):

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        set_attrs_for_fields(self.fields, self.get_default_attrs())

    def get_default_attrs(self):
        return {
                forms.TextInput: {'class': 'form-control'},
                forms.EmailInput: {'class': 'form-control'},
                forms.PasswordInput: {'class': 'form-control'},
            }

或者,您可以在此处使用自定义过滤器检查:Adding css classes to formfields in Django Templates