更新时间:2023-02-19 21:01:16
如果我正确理解你,你想做的是覆盖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!