[Django]-Change a Django form field to a hidden field

222๐Ÿ‘

โœ…

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:

field = form.fields['field_name']
field.widget = field.hidden_widget()

but Iโ€™m not sure it will protect save method on post.

edit: field with multiple values donโ€™t supports HiddenInput as input type, so use default hidden input widget for this field instead.

๐Ÿ‘คchristophe31

265๐Ÿ‘

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

๐Ÿ‘คsemente

90๐Ÿ‘

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.

๐Ÿ‘คShay Rybak

54๐Ÿ‘

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.

๐Ÿ‘คrych

41๐Ÿ‘

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

9๐Ÿ‘

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"
๐Ÿ‘คZags

3๐Ÿ‘

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

๐Ÿ‘คAnonymousUser

2๐Ÿ‘

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

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

2๐Ÿ‘

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()
๐Ÿ‘คAmir jodat

1๐Ÿ‘

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

1๐Ÿ‘

Disclaimer: I am a junior in Django. This answer is a working solutions; however, it may contain some sub-optimal practices. If that is the case, please let me know in the comments, and I will adjust it.

To expand on Rybakโ€™s and Zagsโ€™s answers, if you want to use the HiddenInput field in multiple places, you could create a custom hidden field class.

class MyHiddenCharField(forms.CharField):
    def __init__(self, *, required=False, **kwargs):
        self.required = required
        self.widget = forms.HiddenInput()
        super().__init__(required=False, **kwargs)
๐Ÿ‘คJakub Holan

-4๐Ÿ‘

You can just use css :

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

This will make the field and its label invisible.

๐Ÿ‘คuser20310

Leave a comment