Django Form – Selectively hide fields

The model forms has an option to specify an array exclude with fields that you’d like to hide on the form. But for a regular form, it’s much easier. Here’s how it can be implemented in a form.

class ExtendLicenseForm(forms.Form):
    extension_days = forms.IntegerField(required=True, help_text='License can be extended for a maximum of 30 days.')
    # Below is the field that I'd like to show in the form if the kwargs passed in value is True
    upload_tenant_license = forms.BooleanField(required=False, label='Upload license', help_text='Select option if you would like to automatically upload the extended license to the tenant.')
    def __init__(self, *args, **kwargs):
        upload_tenant_lic_opt = kwargs.pop('upload_tenant_license') if 'upload_tenant_license' in kwargs else None
        super(ExtendLicenseForm, self).__init__(*args, **kwargs)
        if not upload_tenant_lic_opt:
            # Hide the form field if the flag is False
            self.fields['upload_tenant_license'].widget = forms.HiddenInput()



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s