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.
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 superuser
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With