Django(1.11.10)集成Grappelli(2.11.1):自定义仪表盘按组显隐元素
解决Grappelli仪表盘无request时按用户组显示URL元素的问题
这个场景我之前在做Grappelli自定义仪表盘时碰到过,其实不用纠结拿不到request的问题——Grappelli的Dashboard类本身就提供了一个init_with_context方法,每次渲染仪表盘时都会传入包含request的上下文,刚好可以用来判断用户组!
下面是具体的实现步骤:
1. 改造自定义Dashboard类
在你的自定义Dashboard类里,重写init_with_context方法,通过上下文获取当前用户,判断其所属组后再决定是否添加受限制的URL模块:
from grappelli.dashboard import Dashboard from grappelli.dashboard.modules import LinkList from django.utils.translation import ugettext_lazy as _ class CustomDashboard(Dashboard): def init_with_context(self, context): # 先添加所有用户都能看到的公共模块 self.children.append(LinkList( _('通用导航'), column=1, collapsible=False, children=[ {'title': _('后台首页'), 'url': '/admin/'}, {'title': _('用户管理'), 'url': '/admin/auth/user/'}, ] )) # 从上下文获取当前用户 current_user = context['request'].user # 判断用户是否属于指定组(替换成你的目标组名) if current_user.groups.filter(name='专属管理员组').exists(): # 如果是目标组用户,添加受限制的URL模块 self.children.append(LinkList( _('专属功能'), column=1, collapsible=False, children=[ {'title': _('特殊页面'), 'url': '/admin/special-operation/'}, ] )) # 可选:如果要让超级用户也能看到,加上这个判断 # if current_user.is_superuser or current_user.groups.filter(name='专属管理员组').exists():
2. 注册自定义Dashboard
确保在你的admin.py里注册这个自定义仪表盘:
from django.contrib import admin from .dashboard import CustomDashboard # 替换默认的Grappelli仪表盘 admin.site.dashboard = CustomDashboard()
关键说明
init_with_context是Grappelli Dashboard的核心方法,专门用来根据当前请求上下文动态初始化仪表盘内容,所以这里能直接拿到context['request']进而获取用户。- 推荐用组ID代替组名查询(比如
current_user.groups.filter(id=2).exists()),避免后续组名修改导致功能失效。 - 如果需要多个组可见,可以扩展过滤条件,比如
current_user.groups.filter(name__in=['组1', '组2']).exists()。
这样就能完美实现:只有指定组的用户登录后能看到那个特殊URL元素,其他用户完全看不到这个模块。
内容的提问来源于stack exchange,提问作者Naaim Iss
相关产品推荐
相关产品推荐

