guettli
guettli

Reputation: 27069

Hide Model in Django Admin according to value in DB

I want to hide a model in the django admin interface according to a value in the database.

My first solution was to add this to the ready() handler of the app:

    from foo.models import MyModel
    if MyModel.objects.filter(...).exists():
        from foo.models import ModelToHide
        admin.site.unregister(ModelToHide)

Above solutions works ... except:

This fails in CI.

If CI builds a new system from scratch, the database table of MyModel does not exist yet:

Any hints how to solve this?

Upvotes: 10

Views: 240

Answers (1)

solarissmoke
solarissmoke

Reputation: 31494

I think the solution lies in this bit of the admin logic.

So you would provide a custom ModelAdmin for your model, and then override get_model_perms to do something like this in admin.py:

class MyModelAdmin(admin.ModelAdmin):

    def get_model_perms(self, request):
        # Do your check here - if you want to hide the model from the admin then...
         return {
             'add': False,
             'change': False,
             'delete': False,
         }

admin.site.register(MyModel, MyModelAdmin)

Django checks to see if any of these perms are True - if not then it will hide the model from view.

Upvotes: 13

Related Questions