覆盖Django表格中的标签
问题描述:
我有3个部分具有相同的字段,除了“标题”字段上的标签。 对于他们所有我使用相同的Django窗体。覆盖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')
我觉得应该是'超(InvoiceContentForm,个体经营)',但除此之外,就像一个魅力,谢谢!将在几分钟内准备就绪。 – Pythonist
@pythonist,python 3不需要args,但是如果你使用python 2.7,你会正确的。别担心! – Sayse