不同的字段集和管理形式取决于“请求”

时间:2013-10-22 04:13:35

标签: django django-forms django-admin

如何根据admin-form对象定义需要admin-fieldsetsrequest? 例如:

我有一些模特:

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

我在user.profile中的字段为roleadministratorownerseller) 我希望依赖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

1 个答案:

答案 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()方法,这样您就可以访问该请求。