Hidden field in Django Model

Viewed 42459

A while back I made a Model class. I made several ModelForms for it and it worked beautifully.

I recently had to add another optional (blank=True, null=True) field to it so we can store some relationship data between Users. It's essentially a referral system.

The problem is adding this new field has meant the referral field shows up where I haven't changed the ModelForms to exclude it. Normally this would just mean an extra 10 minutes going through and excluding them but in this case, due to project management politics out of my control, I only have control over the Models for this application.

Can I either:

  • Set the field to auto-exclude?
  • Set it so it renders as a hidden (acceptable if not perfect)?
4 Answers

If you have access to the template you could render it as a hidden field with the following code:

{{ form.field_name.as_hidden }}

instead of the standard:

{{ form.field_name }}

from the docs on Using a subset of fields on the form:

Set editable=False on the model field. As a result, any form created from the model via ModelForm will not include that field.

Related