Django ModelForm to have a hidden input

前端 未结 4 808
孤城傲影
孤城傲影 2020-12-01 02:03

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

相关标签:
4条回答
  • 2020-12-01 02:22

    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 }}" />

    0 讨论(0)
  • 2020-12-01 02:23

    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()}
    
    0 讨论(0)
  • 2020-12-01 02:36

    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()
    
    0 讨论(0)
  • 2020-12-01 02:41

    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'
    
    0 讨论(0)
提交回复
热议问题