组织Django fieldsets的最佳方式

时间:2016-06-30 16:24:40

标签: python django django-admin

因此,我正在使用基于用户权限级别的可自定义字段集创建django管理视图。组织字段集以减少代码重复的最佳方法是什么?

目前,对于2个不同的字段集,我设置如下:

standard_fieldsets = (
        (None, {'fields': ('email', 'password')}),
        (_('Permissions'), {
         'fields': ('is_staff', 'is_superuser', 'groups', 'permissions')}),
        (_('Dates'), {'fields': ('last_login',)}),
    )
perm1_fieldsets = (
        (None, {'fields': ('email', 'password')}),
        (_('Dates'), {'fields': ('last_login',)}),
    )

组织字段集的目的是选择它们,如下所示:

def get_fieldsets(self, request, obj=None):
        if # user has permission 1:
            self.fieldsets = self.perm1_fieldsets
        else:
            self.fieldsets = self.standard_fieldsets

        if not obj:
            return self.add_fieldsets
        return super().get_fieldsets(request, obj)

1 个答案:

答案 0 :(得分:1)

如果字段集内的字段始终相同且顺序相同,则可以执行以下操作:

class SomeAdmin(admin.ModelAdmin):
    fieldsets = {
        'base': (None, {'fields': ('email', 'password')}),
        'permissions': (
            _('Permissions'), {
                'fields': ('is_staff', 'is_superuser', 'groups', 'permissions'),
            }),
        'dates': (_('Dates'), {'fields': ('last_login',)}),
    }
    add_fieldsets = ('base', 'permissions')
    standard_fieldsets = add_fieldsets + ('dates',)
    perm1_fieldsets = ('base', 'dates')

    def get_fieldsets(self, request, obj=None):
        if not obj:
            fieldsets = self.add_fieldsets
        elif user_has_permission(1):
            fieldsets = self.perm1_fieldsets
        else:
            fieldsets = self.standard_fieldsets
        return [self.fieldsets[x] for x in fieldsets]