I have two ModelAdmin
s in my admin.py
.
Each have the exact same permission methods (has_view_permission
, has_add_permission
, has_change_permission
, has_delete_permission
, has_module_permission
).
Is there a way I could make this more DRY?
admin.py
:
class FirstAdmin(admin.ModelAdmin):
list_display = (
'id',
'title',
'author'
)
def has_view_permission(self, request, obj=None):
if request.user.is_admin:
return True
def has_add_permission(self, request):
if request.user.is_admin:
return True
def has_change_permission(self, request, obj=None):
if request.user.is_admin:
return True
def has_delete_permission(self, request, obj=None):
if request.user.is_admin:
return True
def has_module_permission(self, request):
if request.user.is_admin:
return True
class SecondAdmin(admin.ModelAdmin):
list_display = (
'id',
'category',
)
def has_view_permission(self, request, obj=None):
if request.user.is_admin:
return True
def has_add_permission(self, request):
if request.user.is_admin:
return True
def has_change_permission(self, request, obj=None):
if request.user.is_admin:
return True
def has_delete_permission(self, request, obj=None):
if request.user.is_admin:
return True
def has_module_permission(self,request):
if request.user.is_admin:
return True
CodePudding user response:
Yes, you can easily do that using a class mixin, I've also managed to reduce the method body to one line.
Here's how:
class AdminUserPermissionMixin:
def has_view_permission(self, request, obj=None):
return request.user.is_admin
def has_add_permission(self, request):
return request.user.is_admin
def has_change_permission(self, request, obj=None):
return request.user.is_admin
def has_delete_permission(self, request, obj=None):
return request.user.is_admin
def has_module_permission(self, request):
return request.user.is_admin
class FirstAdmin(AdminUserPermissionMixin, admin.ModelAdmin):
list_display = (
'id',
'title',
'author'
)
class SecondAdmin(AdminUserPermissionMixin, admin.ModelAdmin):
list_display = (
'id',
'category',
)