0

I have 3 sections with identical fields, except for label on "title" field. For all of them I'm using same Django Form.

In views I have:

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)

My form:

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(),
)
(...)

Is there any way I can change title's label on InvoiceContentForm() while assigning it to context.section1 = InvoiceContentForm()?

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
Pythonist
  • 677
  • 5
  • 28

1 Answers1

4

You need to override its constructor

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

context.section1 = InvoiceContentForm('foo')
Sayse
  • 42,633
  • 14
  • 77
  • 146
  • 1
    I think it should be `super(InvoiceContentForm, self)`, but apart from that works like a charm, thank you! Will mark ready in few minutes. – Pythonist Feb 26 '17 at 11:02
  • @pythonist, python 3 doesnt require the args, but yes you're correct if your using python 2.7 you will need that. No worries! – Sayse Feb 26 '17 at 12:01