【问题标题】:Override label in Django Forms覆盖 Django 表单中的标签
【发布时间】:2017-07-16 23:47:42
【问题描述】:

我有 3 个部分具有相同的字段,但“标题”字段上的标签除外。 对于他们所有人,我都使用相同的 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()

【问题讨论】:

    标签: python django python-2.7 django-forms


    【解决方案1】:

    你需要重写它的构造函数

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

    【讨论】:

    • 我认为应该是super(InvoiceContentForm, self),但除此之外,它就像一个魅力,谢谢!将在几分钟内标记就绪。
    • @pythonist,python 3 不需要 args,但是是的,如果您使用 python 2.7,您将需要它,这是正确的。不用担心!
    猜你喜欢
    • 2018-01-01
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 2020-12-01
    • 2020-08-01
    • 1970-01-01
    • 2013-05-22
    • 2013-11-09
    相关资源
    最近更新 更多