Conditionally show and hide a form field and set the field value

随声附和 提交于 2019-11-30 21:18:46

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)

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.

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