how to hide one field when another is selected?

Forms.py: I want to hide job_role field when user_type= admin selected in ‘is_superuser’ field

class CreateUserForm(HelperForm):
    USER_TYPE_CHOICES = (
        (False, 'Employee'),
        (True, 'Admin'),
    )
    first_name = forms.CharField(
        label="First Name",
        max_length=30,
        required=True,
        validators=[firstNameValidator]
    )
    last_name = forms.CharField(
        label="Last Name",
        max_length=30,
        required=True,
        validators=[lastNameValidator]
    )
    email = forms.EmailField(
        label="Email",
        required=True,
        validators=[emailValidator]
    )
    job_role = forms.ModelChoiceField(queryset=Group.objects.all())
    is_superuser = forms.ChoiceField(label='User Type', choices=USER_TYPE_CHOICES)
    is_active = forms.BooleanField(initial=False, required=False, widget=forms.HiddenInput())

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'username',
                  'email', 'is_superuser', 'job_role', 'is_active')

I am not aware of any facility within Django providing that feature. It would take a little bit of JavaScript embedded within your page to hide/show a field depending upon the value of a different field.

1 Like

KenWhitesell, Thanks for your reply

How can i get selected value in user update form, please give me answer for this also if possible

Are you referring to doing this in JavaScript in the browser to handle the hiding of a field? Or are you referring to how you need to handle the form once it has been submitted to Django?

If the former, it’s highly dependent upon whether or not you’re using a JavaScript library or framework to provide client-side UI enhancements, such as jQuery. We use jQuery where I work, so that’s what I’m most familiar with, but it might be a bit much if this is the only enhancement you’re looking to add to an otherwise plain form. (If the latter, then I would end up referring you to a variety of documentation addressing form handling.)