So I have my TagStatus model. I\'m trying to make a ModelForm for it. However, my form requires that the hidden input be populated with the {{ tag.name }}. I\'ve been lookin
There are 3 possible ways (AFAIK) to render hidden fields in Django -
1. You could declare a field normally in forms.py
but in your templates html file use {{ form.field.as_hidden }}
2. in forms.py
directly use hidden input widget.
class MyForm(forms.Form):
hidden_field = forms.CharField(widget=forms.HiddenInput())
Once you make the field a hidden input, you could populate the value of the field in templates. Now your hidden field is ready for rendering.
3. Regular form equivalent (thanks to @Modelesq for sharing this nugget). Here no Django is involved. Changes are done at HTML template level. <input type="hidden" name="tag" value="{{ tag.name }}" />
To make a field in a ModelField a hidden field, use a HiddenInput widget. The ModelForm uses a sensible default widget for all the fields, you just need to override it when the object is constructed.
class TagStatusForm(forms.ModelForm):
class Meta:
model = TagStatus
widgets = {'tag': forms.HiddenInput()}
I was looking for a way to HIDE ALL INPUTS :
class TagStatusForm(forms.ModelForm):
class Meta:
model = TagStatus
def __init__(self, *args, **kwargs):
super(TagStatusForm, self).__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget = forms.HiddenInput()
I posted a way to do it with generic class-based views here:
from django.forms import HiddenInput
from django.forms.models import modelform_factory
_patient_create_form = modelform_factory(
models.Patient,
fields=['name', 'caregiver_name', 'sex', 'birth_date',
'residence', 'country'],
widgets={'country': HiddenInput()})
class PatientCreate(LoginRequiredMixin, UserOrgRequiredMixin, CreateView):
form_class = _patient_create_form
template_name = 'healthdbapp/patient_form.html'