Django ModelAdmin与请求/基于用户的对fieldsets的限制(需要为Thread Safe) [英] Django ModelAdmin with request/user based restrictions on the fieldsets (needs to be Thread Safe)
问题描述
我有几个非常自定义的Django ModelAdmin,如果用户是超级用户,我想添加额外的字段。我发现有人说要覆盖像这样的get_fieldsets方法
I have several very customized Django ModelAdmins that I would like to add extra field(s) if the user is a superuser. I found somewhere that someone said to override the get_fieldsets method like this
def get_fieldsets(self, request, obj=None):
fieldsets = super(PageAdmin, self).get_fieldsets(request, obj)
if request.user.is_superuser:
fieldsets[0][1]['fields'].insert(0,'group')
fieldsets[0][1]['fields'].insert(2,'is_live')
else:
groups = request.user.page_groups.filter(
is_live = True,
)
if groups.count() > 1:
fieldsets[0][1]['fields'].insert(0,'group')
return fieldsets
这个工作(一种),我喜欢使用get_fieldsets,因为它可以让我把这些字段分组成fieldets。
我也在这个管理员上使用get_form,因为该表单有几个用户特定的表单字段,它们基于用户的查询。
This works (sort of) and I like using get_fieldsets because it lets me group the fields into fieldsets. I also use get_form on this admin because the form has several user specific form fields that have querysets based on the user.
def get_form(self, request, obj=None, **kwargs):
if request.user.is_superuser:
return PageForm
else:
form = RestrictedPageForm
form.owner = request.user #(this may be a bad way to do this but it works I think)
return form
现在我遇到了我认为是线程问题的问题。
Now I am running into what I believe to be Threading issues.
如果您快速刷新change_form页面在浏览器中,您将看到多个组或is_live字段。
What happens is that if you quickly refresh the change_form page in the browser you will see multiple "group" or "is_live" fields in the form.
我真的很喜欢利用管理员让我无需写任何东西,我找不到如何正确地做到这一点。任何帮助或建议将不胜感激!
I have really liked leveraging the Admin to keep me from having to write everything but I cannot find out how to do this correctly. Any help or suggestions would be greatly appreciated!
推荐答案
问题是您正在更改即使
中的fieldets 属性不是线程安全的em>是。 get_fieldsets
c
The problem is that you're literally changing the fieldsets
attribute on the ModelAdmin
, which is not thread-safe, even though get_fieldsets
is.
最好的方法是指定单独的字段集:
The best way to do this is to specify separate fieldsets:
fieldsets = (...)
restricted_fieldsets = (...)
然后:
Then:
def get_fieldsets(self, request, obj=None):
if some_condition:
return self.restricted_fieldsets
else:
return super(MyModelAdmin, self).get_fieldsets(request, obj=obj)
这篇关于Django ModelAdmin与请求/基于用户的对fieldsets的限制(需要为Thread Safe)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!