Django - 权限和配置文件

发布于 2024-10-10 00:50:32 字数 561 浏览 9 评论 0原文

我有几个不同的个人资料。我想将权限与这些配置文件关联。我这样做是这样的:

class StudentProfile(UserProfile):
    school = models.CharField(max_length=30)
    class Meta:
        permissions = (
            ("is_student","Can access student pages"),
        )

但是,当我尝试在该配置文件对象上使用 has_perm 检查该权限是否存在时,我收到错误“'StudentProfile'对象没有属性'has_perm'”我不应该检查权限这样?我已经阅读了文档,这就是我认为我应该做的

编辑:再次阅读文档后,似乎 has_perm 是属于用户而不是他们的个人资料的方法。但是,当我尝试显示权限时:

print user.get_all_permissions()

我得到一个空集。我不应该看到类似“appname.is_student”的内容吗

I have a couple of different profiles. I want to associate permissions with these profiles. I've done so like this:

class StudentProfile(UserProfile):
    school = models.CharField(max_length=30)
    class Meta:
        permissions = (
            ("is_student","Can access student pages"),
        )

however, when I try and check if that permission exists using has_perm on that profile object, I get an error "'StudentProfile' object has no attribute 'has_perm'" am I not supposed to check for permissions in this way? I've read the docs and that's what I thought I was supposed to do

Edit: After reading the docs again, it seems that has_perm is a method belonging to Users and NOT their profiles. However, when I try to show the permissions:

print user.get_all_permissions()

I get an empty set. Shouldn't I see something like "appname.is_student"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

末蓝 2024-10-17 00:50:32

.has_permUser 对象上的方法,而不是 UserProfile 对象上的方法。如果您尝试验证用户是否拥有 has_student 权限,则需要执行以下操作:

user.has_perm('profiles.is_student')

假设您的 StudentProfile 模型位于 profiles 应用程序中。

编辑:要解决您重新表述的问题,您应该以正常方式向组或特定用户分配权限,并使用User.has_perm。你的后一个例子完全违背了 Django 权限系统的观点。

.has_perm is a method on the User object, not on a UserProfile object. If you are trying to validate that a user has the permission has_student, you'd need to do something like this:

user.has_perm('profiles.is_student')

assuming that your StudentProfile model is in a profiles application.

EDIT: To address your rephrased question, you should assign permissions the normal way, either to the group or to a particular user, and use User.has_perm. Your latter example goes completely against the point of the Django permission system.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文