Conditionally show and hide the 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( required=True, max_length=30, label=_("Name") ) is_manager = forms.BooleanField( required=True, label=_("Is Manager") ) 

I use this form in two places on my site. One of the places I would like to display the form and all its fields except the is_manager field, but I would like to set the default value of this field to True . Elsewhere, I would like to display the form and all its fields, including the is_manager field, and I would like it to have a default value of False.

How can i do this? This seems to be a trivial thing, but I cannot understand it.

Thanks.

+6
source share
2 answers

You can use the __init__ form method to hide (or remove) 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) 
+12
source

If the functions are different, you can use the inheritance of one form from another and display sutyably (for example, exception fields).

In addition, the init method can be created to accept arguments, and this can be used to initialize the values โ€‹โ€‹of a form field.

+1
source

Source: https://habr.com/ru/post/892893/


All Articles