Search code examples
djangodjango-admin

How to hide some fields in django-admin?


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?


Solution

  • You are to create admin.py in your module (probably book)

    class BookAdmin(admin.ModelAdmin):
        list_display = ("pk", "get_title_or_nothing")
    

    In Book class:

    class Book:
        ...
        def get_title_or_nothing(self):
            if self.type == WEIRD_TYPE:
                return ""
            return self.title
    

    UPDATED:

    class BookAdmin(admin.ModelAdmin):
        list_display = ("pk", "get_title_or_nothing")
    
        def get_form(self, request, obj=None, **kwargs):
            if obj.type == "1":
                self.exclude = ("title", )
            form = super(BookAdmin, self).get_form(request, obj, **kwargs)
            return form