Bạn có thể sử dụng như sau:
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__]
field.widget.attrs = default_widget_attr
except KeyError:
pass
class DefaultAttrForm(forms.Form):
def __init__(self, *args, **kwargs):
super(DefaultAttrForm, self).__init__(*args, **kwargs)
set_attrs_for_fields(self.fields, self.get_default_attrs())
def get_default_attrs(self):
'''
Child class should overwrite this method and return dict with example format
{forms.TextInput: {'class': 'my_value'}}
where keys, are widget classes for which default attrs will be set.
'''
raise NotImplementedError()
class DefaultAttrModelForm(ModelForm):
def __init__(self, *args, **kwargs):
super(DefaultAttrModelForm, self).__init__(*args, **kwargs)
set_attrs_for_fields(self.fields, self.get_default_attrs())
def get_default_attrs(self):
'''
Child class should overwrite this method and return dict with example format
{forms.TextInput: {'class': 'my_value'}}
where keys, are widget classes for which default attrs will be set.
'''
raise NotImplementedError()
Bây giờ, mỗi khi bạn muốn sử dụng attrs mặc định cho một số widget, bạn chỉ cần tạo class thừa hưởng từ DefaultAttrForm hoặc DefaultAttrModelForm và overwrite method get_default_attrs
. Ví dụ cho mẫu Django bình thường:
class MyForm(DefaultAttrForm):
my_field1 = forms.CharField(widget=forms.TextInput())
my_field2 = forms.CharField(widget=forms.PasswordInput(attrs={'my_non_default': 'Non default'}))
def get_default_attrs(self):
# all fields with widget TextInput will have
# default attrs set to {'class': 'my_value'}
return {forms.TextInput: {'class': 'my_value'},
}
In [1]: form = MyForm()
In [2]: form.fields['my_field1'].widget.attrs
Out[2]: {'class': 'my_value'}
In [3]: form.fields['my_field2'].widget.attrs
Out[3]: {'my_non_default': 'Non default'}
Đối với mẫu hình thức sử dụng như sau:
class MyModelForm(DefaultAttrModelForm):
class Meta:
model = my_model
def get_default_attrs(self):
# all fields with widget TextInput will have
# default attrs set to {'class': 'my_value'}
return {forms.TextInput: {'class': 'my_value'},
}
In [1]: form = MyModelForm()
In [2]: form.fields['my_field1'].widget.attrs
Out[2]: {'class': 'my_value'}
In [3]: form.fields['my_field2'].widget.attrs
Out[3]: {'my_non_default': 'Non default'}
Nguồn
2010-09-26 19:49:15
bạn có thể ghi đè init bằng trình trang trí không? cũng có, nên có một tuyên bố nếu trước attrs.update() bởi vì tôi muốn thiết lập một mặc định hơn là ghi đè lên những gì có thể đã có. – Kevin
Tôi nghĩ rằng trang trí được dự định sẽ được sử dụng với callables, trọng các nhà xây dựng nên được thực hiện thông qua cơ chế thừa kế bình thường. Trong django nó không phải là không phổ biến để có một số chức năng trở về lớp học, các chức năng này thường được gọi là 'nhà máy'. Cập nhật với điều kiện "if" (chưa được kiểm tra). –