ModelForms&干占位符

时间:2017-06-01 21:37:54

标签: django

所以我想用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时,占位符字典无处可寻。为什么这样,我可以做到这一点?

1 个答案:

答案 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