Pythonist
Pythonist

Reputation: 697

Override label in Django Forms

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()?

Upvotes: 0

Views: 2054

Answers (1)

Sayse
Sayse

Reputation: 43330

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')

Upvotes: 4

Related Questions