Conditionally Show And Hide A Form Field And Set The Field Value
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(
Solution 1:
You could use the form's __init__
method to hide (or delete) the field, i.e.
classPersonnelForm(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)
Post a Comment for "Conditionally Show And Hide A Form Field And Set The Field Value"