How to hide some fields in django-admin?

pmoniq picture pmoniq · Apr 26, 2012 · Viewed 55.6k times · Source
class Book(models.Model):
    title = models.CharField(..., null=True)
    type = models.CharField(...)
    author = models.CharField(...)

I have a simple class in models.py. In admin I would like to hide title of the book (in book details form) when type of the saved book is 1. How do this in a simplest way?

Answer

Lorenz Lo Sauer picture Lorenz Lo Sauer · Sep 3, 2013

For Django > 1.8 one can directly set the fields to be excluded in admin:

 class PostCodesAdmin(admin.ModelAdmin):
      exclude = ('pcname',)

Hidden fields are directly defined in Django's ORM by setting the Field attribute: editable = False

e.g.

class PostCodes(models.Model):
  gisid  = models.IntegerField(primary_key=True)
  pcname = models.CharField(max_length=32, db_index=True, editable=False)
  ...

However, setting or changing the model's fields directly may not always be possible or advantegous. In principle the following admin.py setup could work, but won't since exclude is an InlineModelAdmin option.

class PostCodesAdmin(admin.ModelAdmin):
     exclude = ('pcname',)
....

A solution working at least in Django 1.4 (and likely later version numbers) is:

class PostCodesAdmin(admin.ModelAdmin):
  def get_form(self, request, obj=None, **kwargs):
      form = super(PostCodesAdmin, self).get_form(request, obj, **kwargs)
      del form.base_fields['enable_comments'] 
      return form

For the admin list-view of the items, it suffices to simply leave out fields not required: e.g.

class PostCodesAdmin(admin.ModelAdmin):
  list_display = ('id', 'gisid', 'title', )