2017-02-26 126 views
0

我有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()

回答

1

你需要重寫它的構造

class InvoiceContentForm(forms.Form): 
    def __init__(self, title, *args, **kwargs): 
      super().__init__(*args, **kwargs) 
      self.fields['title'].label = title 

context.section1 = InvoiceContentForm('foo') 
+1

我覺得應該是'超(InvoiceContentForm,個體經營)',但除此之外,就像一個魅力,謝謝!將在幾分鐘內準備就緒。 – Pythonist

+0

@pythonist,python 3不需要args,但是如果你使用python 2.7,你會正確的。別擔心! – Sayse