给 Django Admin 添加 read only 权限
通过查看django源代码我们可以看到权限是在ModelAdmin中定义的,所以我们只需继承ModelAdmin并添加read only权限即可。
在项目app下创建custom_model_admin.py
代码如下:
from django.contrib import admin
from django.contrib.auth.models import Permission
class CustomModelAdmin(admin.ModelAdmin):
def has_view_permission(self, request, obj=None):
opts = self.opts
view_permission = 'view_%s' %self.model._meta.module_name
return request.user.has_perm(opts.app_label + '.' + view_permission)
def has_change_permission(self, request, obj=None):
if hasattr(self,'has_change'):
if self.has_change:
return True
return super(CustomModelAdmin,self).has_change_permission(request, obj)
def get_model_perms(self, request):
value = super(CustomModelAdmin,self).get_model_perms(request)
value['view'] = self.has_view_permission(request)
return value
def changelist_view(self, request, extra_context=None):
if self.has_view_permission(request, None):
self.has_change = True
result = super(CustomModelAdmin,self).changelist_view(request, extra_context)
self.has_change = False
return result
代码很短,就不过多讲解了,参考django\contrib\admin\options.py
可直接在自己的项目中使用,注册admin时只需继承CustomModelAdmin即可,例如:
from django.contrib import admin
from your_app.custom_model_admin import CustomModelAdmin
from models import *class YourModelAdmin(CustomModelAdmin):
list_filter = ('status',)
list_display = ('username', 'email','status','last_login','from_ip',)
search_fields = ('username', 'email',)
ordering = ['-id']admin.site.register(YourModel, ComUserAdmin)
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。