有条件地显示和隐藏表单字段并设置字段值
我的 Django 中有一个看起来像这样的表单:
class PersonnelForm(forms.Form):
"""
Form for creating a new personnel.
"""
username = forms.RegexField(
required=True, max_length=30, label=_("Name")
)
is_manager = forms.BooleanField(
required=True, label=_("Is Manager")
)
我在网站的两个地方使用了这个表单。其中之一是,我想显示表单及其除 is_manager
字段之外的所有字段,但我想将此字段的默认值设置为 True
。在其他地方,我想显示表单及其所有字段,包括 is_manager
字段,并且我希望它具有默认值 False。
如何我能做到吗?似乎是一件微不足道的事情,但我无法弄清楚。
谢谢。
I have a form in my Django that looks something like this:
class PersonnelForm(forms.Form):
"""
Form for creating a new personnel.
"""
username = forms.RegexField(
required=True, max_length=30, label=_("Name")
)
is_manager = forms.BooleanField(
required=True, label=_("Is Manager")
)
I use this form in two places in my site. One one of the places, I'd like to display the form and all of its fields except the is_manager
field but I would like to set the default value of this field to True
. In the other place, I'd like to display the form and all of its fields including the is_manager
field and I would like it to have a default value of False.
How can I accomplish this? Seems to be a trivial thing but I can't figure it out.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用表单的
__init__
方法来隐藏(或删除)该字段,即You could use the form's
__init__
method to hide (or delete) the field, i.e.如果功能不同,您可以使用从另一种形式继承并适当显示(即排除字段)。
另外,Form 的 init 方法可以接受参数,这可以用来初始化表单的字段值。
If the functionalities are different, you can use inherit one form from the other and display sutiably(i.e exclude fields).
Also, Form's init method can be made to take arguments, and this can be used to initialize the form's field values.