0

我如何定义需要admin-formadmin-fieldsets取决于request对象?例如:

我有一些模型:

# models.py
class Shop(models.Model):
    name = models.CharField(...)
    description = models.TextField(...)
    params = models.SomeField(...)

我的字段user.profilerole( 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
4

1 回答 1

3

您需要覆盖模型管理员的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()方法,这将使您能够访问请求。

于 2013-10-22T04:21:47.033 回答