在除超级用户之外的用户中排除Django管理员中的字段 [英] Exclude fields in Django admin for users other than superuser

查看:313
本文介绍了在除超级用户之外的用户中排除Django管理员中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 MyUser 类与 PermissionsMixin user.is_superuser 等于 True 仅适用于超级用户。我想在我的 admin.py 中做类似的事情:

  if request.user.is_superuser:
fieldsets =(
(无,{'fields':('email','password')}),
('权限,{'fields':('is_admin','is_staff')}),
('Place',{'fields':('place',)}),
日期',{'fields':('last_login',)}),

else:
fieldsets =(
(无,{'fields':(' ','password')}),
#('Permissions',{'fields':('is_admin','is_staff')}),
('Place',{'fields' ('place',)}),
('重要日期',{'fields':('last_login',)}),

/ pre>

基本上,我希望我的用户能够创建其他用户,但不给予他们管理或权限。只有超级用户应该能够这样做。

解决方案

如果我正确理解你,你想做的是覆盖get_form方法为ModelAdmin。基于来自django文档的示例,它将如下所示:

  class MyUserAdmin(admin.ModelAdmin):
def get_form(self,request,obj = None,** kwargs):
self.exclude = []
如果没有request.user.is_superuser:
self.exclude.append('Permissions')#here!
return super(MyUserAdmin,self).get_form(request,obj,** kwargs)

现在你可能需要一点点攻击,也可能会覆盖保存方法。我不久以前做过类似的事情,它并不那么复杂(文档很棒)。



可能有一个更简单的解决方案,但你的问题是一般的,你没有不要分享你的用户模型,所以我无法告诉你如何解决这个问题。我希望这有帮助!


I have a simple MyUser class with PermissionsMixin. user.is_superuser equals True only for superusers. I'd like to be able to do something similar to this in my admin.py:

    if request.user.is_superuser:
        fieldsets = (
            (None, {'fields': ('email', 'password')}),
            ('Permissions', {'fields': ('is_admin','is_staff')}),
            ('Place', {'fields': ('place',)}),
            ('Important dates', {'fields': ('last_login',)}),
        )
    else:
        fieldsets = (
            (None, {'fields': ('email', 'password')}),
            #('Permissions', {'fields': ('is_admin','is_staff')}),
            ('Place', {'fields': ('place',)}),
            ('Important dates', {'fields': ('last_login',)}),
        )

Basically I want my users to be able to create other users, but not give them admin or stuff permissions. Only superusers should be able to do that.

解决方案

If I understand you correctly, what you want to do is override the get_form method for the ModelAdmin. Base on the example from django documentation, it would look something like this:

class MyUserAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        self.exclude = []
        if not request.user.is_superuser:
            self.exclude.append('Permissions') #here!
        return super(MyUserAdmin, self).get_form(request, obj, **kwargs)

Now you might need to hack around a little and maybe override the save method as well. I did something similar not long ago, it's not so complicated (and the docs are fantastic).

There might be a simpler solution but your question is kinda general and you didn't share your user model, so I can't tell you exactly how to work this out. I hope this helps!

这篇关于在除超级用户之外的用户中排除Django管理员中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆