141π
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()}
92π
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 }}" />
- [Django]-How to assign items inside a Model object with Django?
- [Django]-Has Django served an excess of 100k daily visits?
- [Django]-How do I package a python application to make it pip-installable?
3π
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()
- [Django]-Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'
- [Django]-Django 1.5 β How to use variables inside static tag
- [Django]-Django URLs TypeError: view must be a callable or a list/tuple in the case of include()
1π
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'
- [Django]-How do you configure Django to send mail through Postfix?
- [Django]-Easiest way to rename a model using Django/South?
- [Django]-How can I return HTTP status code 204 from a Django view?