views:

1116

answers:

3

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)?
+8  A: 

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.

Ofri Raviv
Magic. Works exactly how I need. Thank you!
Oli
+3  A: 

You could define a custom model field subclass and override the formfield() method to return a field with a HiddenInput widget. See the documentation for custom fields.

Daniel Roseman
Yes, I was looking at this before Ofri's answer. Frankly I'm glad there's a simple way to do what I wanted but of course there are scenarios that do require custom fields. Thanks for your answer.
Oli
+4  A: 

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

{{ form.field_name.as_hidden }}

instead of the standard:

{{ form.field_name }}
Gregor Müllegger
How did you figure out "as_hidden" property? I couldn't find it in the django docs. I too was trying to figure out how to use it and thanks to you now I know.
iHeartDucks
I figured it out by reading through the django source code. I really can recommend looking into django's source. Its really easy to understand and well structured.
Gregor Müllegger