Add a hidden field to a Django Form

How to add a hidden field to a Django Form or a Django ModelForm

Posted Jan. 14, 2019

There are two methods to hide a field in a Django Form, both solutions uses the HiddenInput widget.

If your form is a Django ModelForm, the way to do it is:

from django.db import models
class Player(models.Model):
name = models.CharField(max_length=255)
view raw models.py hosted with ❤ by GitHub
from django import forms
from .models import Player
class PlayerForm(forms.ModelForm):
class Meta:
model = Player
fields = ['name']
widgets = {'name': forms.HiddenInput()}
view raw forms.py hosted with ❤ by GitHub

If you want to define your Django Form from scratch, the solution is:

from django import forms
from .models import Player
class PlayerForm(forms.Form):
name = forms.CharField(widget=forms.HiddenInput())
view raw forms.py hosted with ❤ by GitHub