dan-klasson
dan-klasson

Reputation: 14210

ModelForms & DRY placeholders

So I wanted a DRY way to specify the placeholders for my form fields. So whipped up this 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

This works great as it allows me to do this:

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']

Although this is kinda ugly. I would rather do this:

    class Meta:
        # ...
        placeholders = {
            'name': 'Order Name',
            'order_contacts': 'Send it only to contacts in this group...',
        }

But when I inspect self._meta, the placeholders dict is no where to be found. Why is this and I can I make that work?

Upvotes: 1

Views: 43

Answers (1)

William R. Marchand
William R. Marchand

Reputation: 588

Variables are copied in the _meta attribute at the metaclass level. Only a particuliar list of meta options are copied. If you want to add to the self._meta you will need to subclass the ModelBase metaclass and use your own.

Possible meta options https://docs.djangoproject.com/en/1.11/ref/models/options/

ModelBase metaclass https://github.com/django/django/blob/master/django/db/models/base.py

Upvotes: 1

Related Questions