在admin.StackedInline嵌入式接入模型对象(Access model object

2019-10-20 04:33发布

我试图用一个inlineUserAdminadmin.py我正在寻找一种方法来修改该领域inline基于对象。

ProfileInline

class ProfileInline(admin.StackedInline):
    model = UserProfile
    filter_horizontal = ('user_markets',)
    fk_name = 'user'
    max_num = 1
    can_delete = False
    fields = ('email_role', )
    verbose_name_plural = 'Profile'

UserAdmin

class UserAdmin(UserAdmin):
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', roles, login)
    list_filter = ('groups',)
    inlines = (ProfileInline,)

在这里,我需要修改ProfileInline.fields = ('department','email_role')如果用户属于Sales Group ,别的不管。

我需要一种方法来访问用户Object和更新的fields

Answer 1:

class ProfileInline(admin.StackedInline):
    model = UserProfile
    filter_horizontal = ('user_markets',)
    fk_name = 'user'
    max_num = 1
    can_delete = False
    fields = ('email_role', )
    verbose_name_plural = 'Profile'

    def get_fieldsets(self, request, obj=None):
        fieldsets = super(ProfileInline, self).get_fieldsets(request, obj)

        # fieldsets[0][1]['fields'].remove('email_role')
        fieldsets[0][1]['fields'] = ('department', 'email_role')

        return fieldsets

get_fieldsets方法是您的解决方案。 你有request对象,以便request.user也。



文章来源: Access model object in admin.StackedInline inline