所以我想用DRY方式为表单字段指定占位符。所以掀起了这个Mixin:
class FormPlaceholderMixin(object):
def __init__(self, *args, **kwargs):
super(FormPlaceholderMixin, self).__init__(*args,**kwargs)
for index, placeholder in self.PLACEHOLDERS.iteritems():
self.fields[index].widget.attrs['placeholder'] = placeholder
这很有效,因为它允许我这样做:
class PostcardOrderForm(FormPlaceholderMixin, forms.ModelForm):
PLACEHOLDERS = {
'name': 'Order Name',
'order_contacts': 'Send it only to contacts in this group...',
}
class Meta:
model = PostcardOrder
fields = ['name', 'order_contacts']
虽然这有点难看。我宁愿这样做:
class Meta:
# ...
placeholders = {
'name': 'Order Name',
'order_contacts': 'Send it only to contacts in this group...',
}
但是当我检查self._meta
时,占位符字典无处可寻。为什么这样,我可以做到这一点?
答案 0 :(得分:1)
变量被复制到元类级别的_meta属性中。仅复制元选项的特定列表。如果要添加到self._meta,则需要对ModelBase元类进行子类化并使用自己的类。
可能的元选项 https://docs.djangoproject.com/en/1.11/ref/models/options/
ModelBase元类 https://github.com/django/django/blob/master/django/db/models/base.py