Change a Django form field to a hidden field

Viewed 234707

I have a Django form with a RegexField, which is very similar to a normal text input field.

In my view, under certain conditions I want to hide it from the user, and trying to keep the form as similar as possible. What's the best way to turn this field into a HiddenInput field?

I know I can set attributes on the field with:

form['fieldname'].field.widget.attr['readonly'] = 'readonly'

And I can set the desired initial value with:

form.initial['fieldname'] = 'mydesiredvalue'

However, that won't change the form of the widget.

What's the best / most "django-y" / least "hacky" way to make this field a <input type="hidden"> field?

11 Answers

If you want the field to always be hidden, use the following:

class MyForm(forms.Form):
    hidden_input = forms.CharField(widget=forms.HiddenInput(), initial="value")

If you want the field to be conditionally hidden, you can do the following:

form = MyForm()
if condition:
    form.fields["field_name"].widget = forms.HiddenInput()
    form.fields["field_name"].initial = "value"

Example of a model:

models.py

from django.db import models


class YourModel(models.Model):
    fieldname = models.CharField(max_length=255, default="default")

In your form, you can add widgets with ModelForm. To make it hidden add 'type': 'hidden' as shown below

forms.py

from .models import YourModel
from django import forms


class YourForm(forms.ModelForm):


    class Meta:
        model = YourModel
        fields = ('fieldname',)

        widgets = {
            'fieldname': forms.TextInput(attrs={'type': 'hidden'}),
        }

If you don't know how to add it to your views.py file, here is some videos about it.

If you use Function Based View:

https://www.youtube.com/watch?v=6oOHlcHkX2U


If you use Class Based View:

https://www.youtube.com/watch?v=KB_wDXBwhUA

{{ form.field}}
{{ form.field.as_hidden }}

with this jinja format we can have both visible form fields and hidden ones too.

With render_field is easy {% render_field form.field hidden=True %}

if you want to hide and disable the field to protect the data inside. as others mentioned use the hiddenInput widget and make it disable

in your form init

example:

        if not current_user.is_staff:
           self.base_fields['pictureValid'].disabled = True
           self.base_fields['pictureValid'].widget = forms.HiddenInput()

You can just use css :

#id_fieldname, label[for="id_fieldname"] {
  position: absolute;
  display: none
}

This will make the field and its label invisible.

Related