Override label in Django Forms

こ雲淡風輕ζ 提交于 2020-06-03 09:57:25

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/42467540/override-label-in-django-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!