有条件地显示和隐藏表单字段并设置字段值 [英] Conditionally show and hide a form field and set the field value
问题描述
我的 Django 中有一个表单,看起来像这样:
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")
)
我在我网站的两个地方使用了这个表格.其中一个地方,我想显示表单及其除 is_manager
字段之外的所有字段,但我想将此字段的默认值设置为 True
.在另一个地方,我想显示表单及其所有字段,包括 is_manager
字段,我希望它的默认值为 False.
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.
谢谢.
推荐答案
您可以使用表单的 __init__
方法来隐藏(或删除)该字段,即
You could use the form's __init__
method to hide (or delete) the field, i.e.
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")
)
def __init__(self, *args, **kwargs):
delete_some_field = kwargs.get('delete_some_field', False)
if 'delete_some_field' in kwargs:
del kwargs['delete_some_field']
super(PersonnelForm, self).__init__(*args, **kwargs)
if delete_some_field:
del self.fields['is_manager']
# or
self.fields['is_manager'].widget = something_else
#views.py
form = PersonnelForm(...., delete_some_field=True)
这篇关于有条件地显示和隐藏表单字段并设置字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!