You need to enable JavaScript to run this app. Django中如何判断当前用户是否属于访问的Group模型对象成员?
优惠活动
大模型
产品
解决方案
定价
更多

Django中如何判断当前用户是否属于访问的Group模型对象成员?

问题解决方法

失效原因

UserPassesTestMixin 的 test_func 执行时机早于 DetailView 为实例绑定当前访问对象的步骤,你调用的 self.group 此时尚未被赋值,会触发属性不存在的错误,导致校验逻辑失效。

正确实现

你需要在 test_func 中主动获取当前访问的 Group 对象,再校验用户是否属于该组,推荐重写 get_object 缓存查询结果,避免重复访问数据库:

class GroupDetail(UserPassesTestMixin, generic.DetailView):
    model = models.Group
    context_object_name = 'group'
    template_name = 'projects/group_detail.html'

    def get_object(self, queryset=None):
        # 缓存Group对象,避免test_func和后续渲染逻辑重复查询
        if not hasattr(self, 'group'):
            self.group = super().get_object(queryset)
        return self.group

    def test_func(self):
        current_group = self.get_object()
        # 用主键过滤更可靠,exists()仅判断存在性,查询效率更高
        return self.request.user.profile.group_set.filter(pk=current_group.pk).exists()

可选简化写法

如果你的路由中使用 pk 作为分组的唯一标识参数,也可以直接读取路由参数校验,无需重写 get_object:

def test_func(self):
    return self.request.user.profile.group_set.filter(pk=self.kwargs['pk']).exists()

内容的提问来源于stack exchange,提问作者Iman Zandi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 04:12:03