我正在使用 django-uniform 并使用一些统一的功能,我正在寻找一种直接从表单声明添加 css 类的方法(对于独立小部件)。
(作为奖励,这是我的可重复使用的只读自制混合片段......)
from django import forms
def _get_cleaner(form, field):
def clean_field():
return getattr(form.instance, field, None)
return clean_field
class UniformROMixin(forms.BaseForm):
"""
UniformROMixin, inherits to turn some fields read only
- read_only = list of field names.
"""
def __init__(self, *args, **kwargs):
super(UniformROMixin, self).__init__(*args, **kwargs)
if hasattr(self, "read_only"):
if self.instance and self.instance.pk:
for field in self.read_only:
self.fields[field].widget.attrs['readonly'] = True
self.fields[field].widget.attrs['class'] += "readOnly"
# here I would like to set css class of the label
# created from the self.fields[field].label string
setattr(self, "clean_" + field, _get_cleaner(self, field))
我现在唯一的方法是在我的通用表单模板上添加一些 javascript 并手动添加类。
有什么绝妙的主意吗?