1
所以我想要一個DRY方式來爲我的表單字段指定佔位符。因此颳起了這種密新:ModelForms&DRY佔位符
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
,佔位符字典是沒有被發現的位置。爲什麼這個和我可以做這個工作?