I have a Django form class with around 8 fields. How do I dynamically make all these form fields hidden in one of my views?
Sample:
class FormName(forms.Form):
first_name = forms.CharField(max_length=20, widget=forms.TextInput(attrs="class":"validate[required,first_name]","tabindex":"4"}), required=True)
middle_name = forms.CharField(max_length=20, widget=forms.TextInput(attrs="class":"validate[middle_name]","tabindex":"5"}), required=False)
last_name = forms.CharField(max_length=40, widget=forms.TextInput(attrs="class":"validate[required,last_name]","tabindex":"6"}), required=True)
The reason I want to do this is because I would be using the same form in one of the sign up pages and then again use a similar form elsewhere, where I want these form fields to be hidden. I don’t want to create a separate class duplicating the same fields with “widget=forms.HiddenInput()”.
In cases when you need a form with hidden inputs, you can notify your form, by passing additional variable to the
__init__method like:form = FormName(is_hidden=True). And your form might be looking like follows:In all other cases you can use your form as ussual, without passing
is_hiddenvariable, and it will be using default widgets you defined.Also, you can iterate over
self.fieldsdictionary, and make all your field widgets hidden without having to override each of them manualy