'Change a Django form field to a hidden field

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?



Solution 1:[1]

If you have a custom template and view you may exclude the field and use {{ modelform.instance.field }} to get the value.

also you may prefer to use in the view:

form.fields['field_name'].widget = forms.HiddenInput()

but I'm not sure it will protect save method on post.

Hope it helps.

Solution 2:[2]

This may also be useful: {{ form.field.as_hidden }}

Solution 3:[3]

an option that worked for me, define the field in the original form as:

forms.CharField(widget = forms.HiddenInput(), required = False)

then when you override it in the new Class it will keep it's place.

Solution 4:[4]

Firstly, if you don't want the user to modify the data, then it seems cleaner to simply exclude the field. Including it as a hidden field just adds more data to send over the wire and invites a malicious user to modify it when you don't want them to. If you do have a good reason to include the field but hide it, you can pass a keyword arg to the modelform's constructor. Something like this perhaps:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
    def __init__(self, *args, **kwargs):
        from django.forms.widgets import HiddenInput
        hide_condition = kwargs.pop('hide_condition',None)
        super(MyModelForm, self).__init__(*args, **kwargs)
        if hide_condition:
            self.fields['fieldname'].widget = HiddenInput()
            # or alternately:  del self.fields['fieldname']  to remove it from the form altogether.

Then in your view:

form = MyModelForm(hide_condition=True)

I prefer this approach to modifying the modelform's internals in the view, but it's a matter of taste.

Solution 5:[5]

For normal form you can do

class MyModelForm(forms.ModelForm):
    slug = forms.CharField(widget=forms.HiddenInput())

If you have model form you can do the following

class MyModelForm(forms.ModelForm):
    class Meta:
        model = TagStatus
        fields = ('slug', 'ext')
        widgets = {'slug': forms.HiddenInput()}

You can also override __init__ method

class Myform(forms.Form):
    def __init__(self, *args, **kwargs):
        super(Myform, self).__init__(*args, **kwargs)
        self.fields['slug'].widget = forms.HiddenInput()

Solution 6:[6]

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"

Solution 7:[7]

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

Solution 8:[8]

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

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

Solution 9:[9]

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()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Community
Solution 3 SuperBiasedMan
Solution 4
Solution 5
Solution 6
Solution 7
Solution 8 Ignatious varghese
Solution 9 Amir jodat