除了“标题”字段上的标签外,我有 3 个具有相同字段的部分。对于所有这些,我都使用相同的 Django 表单。
在意见中我有:
def get(self):
context = self.CONTEXT_CLASS(self.MODEL_CLASS)
context.messages = self.get_messages()
context.section1 = InvoiceContentForm()
context.section2 = InvoiceContentForm()
context.section3 = InvoiceContentForm()
self.render_jinja('templates/invoice/add_edit.html', context.as_dict)
我的表格:
class InvoiceContentForm(forms.Form):
"""Form for content of given section in add/edit invoice page."""
DEFAULT_ATTRS = {'class': 'form-control'}
title = forms.CharField(
help_text='Title should be up to 24 characters long.',
label=u'Title',
required=True,
widget=FormTextInput(),
)
(...)
有什么办法可以InvoiceContentForm()
在将其分配给 时更改标题的标签context.section1 = InvoiceContentForm()
吗?
您需要覆盖其构造函数
class InvoiceContentForm(forms.Form):
def __init__(self, title, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['title'].label = title
context.section1 = InvoiceContentForm('foo')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句