Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unregister or register models conditionally in django admin

Is it possible to conditionally register or unregister models in django admin? I want some models to appear in django admin, only if request satisfies some conditions. In my specific case I only need to check if the logged in user belongs to a particular group, and not show the model if the user (even if superuser) is not in the group. I can not use permissions here because, superusers can not be ruled out using permissions. Or, is there a way to revoke permission from even superusers on model.

like image 526
Zahid Avatar asked Mar 17 '23 00:03

Zahid


1 Answers

Permissions on a model can be managed dynamically in ModelAdmin. Override the methods has_add_permission, has_change_permission and has_delete_permission.

class MyModelAdmin(admin.ModelAdmin):
    def has_add_permission(self,request):
        # if request satisfies conditions:
        #   return True
        #else:
        #   return False

Same goes for other two methods. This works for superusers also. If you revoke all three permissions MyModel will not be listed on admin site.

If you only require to hide model entry from admin site, simply override get_model_perms method. You don't have to override permission methods.

def get_model_perms(self, request):
    return {}

However, this method does not revoke permissions from the model. Even if the model is not listed on admin site, it can be accessed by entering url.

like image 118
Zahid Avatar answered Mar 24 '23 11:03

Zahid