私はdjango-uniformを使用しており、いくつかの統一機能を使用するために、フォーム宣言から直接cssクラスを追加する方法を探しています(独立したウィジェット用)。
(おまけとして、ここに私の再利用可能な読み取り専用の自家製 mixin スニペットがあります...)
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 を少し追加し、手動でクラスを追加することです。
素晴らしいアイデアはありますか?