87

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 looking through the docs and I don't know how to make the tag field a hidden input. Perhaps a ModelForm isn't the way to go?

models.py:

class TagStatus(models.Model):
    user = models.ForeignKey(User, null=True, unique=True)
    status = models.CharField(max_length=2, choices=tag_statuses)
    tag = models.ForeignKey(Tag, null=True, blank=True)

    def __unicode__(self):
        return self.status

    def save(self, *args, **kwargs):
        super(TagStatus, self).save(*args, **kwargs)

class TagStatusForm(modelForm):
    class Meta:
        model = TagStatus
        fields = ('status','tag') 
        widgets = {
             'select': Select,
             'tag': ???
        }

django views.py:

@login_required
def tags(request):
    all_tags = Tag.objects.all()
    context = base_context(request)
    if request.method == 'POST':
        if 'status_check' in request.POST:
            status_form = TagStatusForm(request.POST)
            #if request.is_ajax():
            if status_form.is_valid():
                status_form.save()
                response = simplejson.dumps({"status": "Successfully changed status"})
            else:
                response = simplejson.dumps({"status": "Error"})
                return HttpResponse (response, mimetype='application/json')
    status_form = TagStatusForm()
    context['status_form'] = status_form
    context['all_tags'] = all_tags
    return render_to_response('tags/tags.html', context, context_instance=RequestContext(request))

template:

{% for tag in all_tags %}
....
<form class="nice" id="status-form" method="POST" action="">
     {% csrf_token %}
      <input type="hidden" name="status_check" />
      <input type='hidden' name="tag" value="{{ tag.name }}" />
     {{ status_form.status }}
</form>
...
{% endfor %}

How would I go about making a hidden input through a django ModelForm and then populate it through the template?

0

4 Answers 4

142

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()}
1
  • Works with Django 3.2
    – Mark Glass
    Commented Feb 24, 2023 at 9:53
95

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

3
  • 13
    How about I go about populating it? It's regular form equivalent would look like: <input type="hidden" name="tag" value="{{ tag.name }}" />
    – Modelesq
    Commented Apr 3, 2013 at 19:12
  • Did you find how to populate ? using {{ tag.name }} doesn't seem to work. I myself need {{ forloop.counter }}
    – Ehvince
    Commented Jun 25, 2014 at 16:16
  • 4
    Any chance you could add the template side of things?
    – Bono
    Commented Nov 13, 2015 at 13:31
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()
1
  • I get django.core.exceptions.FieldError: 'myField' cannot be specified for myModel model form as it is a non-editable field. So I need to make it editable, but I still want it hidden. Commented Jun 9, 2022 at 5:24
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'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.