如何根据admin-form
对象定义需要admin-fieldsets
和request
?
例如:
我有一些模特:
# models.py
class Shop(models.Model):
name = models.CharField(...)
description = models.TextField(...)
params = models.SomeField(...)
我在user.profile
中的字段为role
(administrator
,owner
,seller
)
我希望依赖user.profile.role
来获取管理界面不同的字段集,例如:
# admin.py
class ShopAdmin(admin.ModelAdmin):
def custom_get_fieldset_and_form_method(self, request, *args, **kwargs):
if request.user.profile.role == 'administator':
self.fieldsets = self.get_default_fieldset_method(self, *args, **kwargs)
elif request.user.profile.role == 'owner':
self.fieldsets = [
(
'Owner Panel', {'fields': ('name', 'description')},
),
(
'Hidden fields', {'classes':('collapse',),'fields': (`params`,)},
)]
else:
# in other, i want to hide `params` field from form
答案 0 :(得分:2)
您需要覆盖模型管理员的get_fieldsets()方法,该方法接收request
对象作为其参数之一:
# NOT TESTED
class ShopAdmin(admin.ModelAdmin):
def get_fieldsets(self, request, obj=None):
profile = YourProfileModel.objects.get(user=request.user)
if profile.role == 'administrator':
fieldsets = self.get_fieldsets(request, obj)
elif profile == 'owner':
fieldsets = (
('Owner Panel', {'fields': ('name', 'description',)}),
('Hidden fields', {'classes':('collapse',),'fields': ('params',)})
)
else:
# additional fieldsets
return fieldsets
如果您想根据用户个人资料添加/排除特定字段,则需要覆盖模型管理员的get_form()方法,这样您就可以访问该请求。