简体   繁体   English

Django Admin:向不同的用户显示不同的模型

[英]Django Admin: Show different models to different users

I have two superusers ( user1 and user2 ) and two models ( ModelA and ModelB ).我有两个超级用户( user1user2 )和两个模型( ModelAModelB )。 In the admin page, I want to show just ModelA to user1 , so user1 can only edit ModelA instances but not ModelB instances.在管理页面中,我只想向user1显示ModelA ,因此user1只能编辑ModelA实例而不能编辑ModelB实例。 Similarly, I want to have user2 able to edit ModelB instances only.同样,我希望user2只能编辑ModelB实例。 Is there a way to achieve this?有没有办法实现这一目标?

That's what the has_change_permission is for.这就是has_change_permission的用途。 You can grant edit permission to specific users.您可以向特定用户授予编辑权限。

class TestAdmin(admin.ModelAdmin):

    def has_change_permission(self, request):
        if request.user.username == 'xyz':
            # Feel free to return false to hide this TestAdmin to xyz user
            return False
        return True

user1 and user2 cannot be superusers if you need to limit their access to ModelA and ModelB respectively.如果需要分别限制对ModelAModelB的访问,则user1user2不能成为超级用户。 So, please refactor that first.所以,请先重构它。

Yes, you can give specific users to specific models access in Django admin interface.是的,您可以在 Django 管理界面中授予特定用户对特定模型的访问权限。 Please have a look at Django docs: Permissions and Authorizations .请查看 Django 文档: 权限和授权

There is also a good tutorial on setting up permissions and groups at: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication还有一个关于设置权限和组的很好的教程: https : //developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication

Let me know if you have confusions after reading along the resources.如果您在阅读资源后有任何困惑,请告诉我。

Thanks!谢谢!

in has_module_permission you can do the following:在 has_module_permission 中,您可以执行以下操作:

def has_module_permission(self, request):
    if request.user.is_superuser:  # show for super user anyway
        return True
    if request.user ... complete the condition:
        return True

you should have something to differentiate between users, like having more attributes for different users (admin, staff, editors) and so on.你应该有一些东西可以区分用户,比如为不同的用户(管理员、员工、编辑)提供更多的属性等等。

if request.user.role = "staff":
    return True

something like that.类似的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM