34

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)?
Oli
  • 235,628
  • 64
  • 220
  • 299

4 Answers4

72

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 }}
gawi
  • 2,843
  • 4
  • 29
  • 44
Gregor Müllegger
  • 4,973
  • 1
  • 23
  • 22
  • 13
    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. – iJK Jun 19 '10 at 01:11
  • 16
    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 Jul 05 '10 at 12:08
  • 2
    Yep, as_hidden is cool- but beware, it doesn't work on multi value fields (eg MultipleChoiceField and possibly others). – s29 Feb 03 '12 at 04:20
57

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
  • 24,375
  • 3
  • 55
  • 55
4

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
  • 588,541
  • 66
  • 880
  • 895
  • 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 Jan 18 '10 at 13:41
1

Though you mentioned that you cannot use exclusion in your case, I think others who come across this answer (like myself, based on the title) may find it helpful.

It is possible to selectively hide fields using exclude in ModelAdmin, here is a snippet from something I'm working on:

class ItemsAdmin(admin.ModelAdmin):
    form = ItemsForm
    actions = None
    list_display = ('item_id', 'item_type', 'item_title', 'item_size', 'item_color',)
    search_fields = ('item_id', 'item_title',)
    inlines = [ImageInline,]
    readonly_fields = ('disable_add_date','disable_remove_date',)
    exclude = ('add_date', 'remove_date',)
    ###.............