Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(
        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.

like image 611
Mridang Agarwalla Avatar asked Jul 16 '11 12:07

Mridang Agarwalla


People also ask

How do you hide form fields based upon user selection?

The Javascript uses jQuery to change the DOM depending on the selections made. Essentially, depending on the conditions of a field answer, you can bulk turn show/hide other components of the form. For validation purposes, some extra attributes are changed depending on the selection.


1 Answers

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)
like image 123
Klaas van Schelven Avatar answered Oct 19 '22 23:10

Klaas van Schelven