【发布时间】:2011-10-21 00:16:56
【问题描述】:
我正在使用 django-uniform 并使用一些统一的功能,我正在寻找一种直接从表单声明添加 css 类的方法(用于独立小部件)。
(作为奖励,这是我的可重复使用的只读自制 mixin sn-p...)
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 并手动添加类。
有什么绝妙的主意吗?
【问题讨论】:
-
我不知道在表单声明中添加 css 类的方法,但我使用过:pypi.python.org/pypi/django-widget-tweaks 方便地将属性添加到模板中的标签标签和表单元素等内容在有意义的情况下进行调整。
-
感谢您的建议。就我而言,我没有完全处理由 django-uniform 完成的模板部分。我仍然可以看到小部件的“渲染”方法是如何工作的并覆盖它......
标签: django django-forms django-crispy-forms