Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 368
guettli Avatar asked Mar 22 '18 08:03

guettli


1 Answers

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.

like image 110
solarissmoke Avatar answered Oct 10 '22 08:10

solarissmoke