在admin.StackedInline内联中访问模型对象

时间:2014-05-22 09:24:07

标签: django admin inline

我正在inline UserAdmin admin.py中使用inline 我正在寻找一种方法来根据对象修改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' 的字段。

ProfileInline

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

UserAdmin

ProfileInline.fields = ('department','email_role')

如果用户属于Sales Group,我需要修改Object,否则无论如何。

我需要一种方法来访问用户fields并更新{{1}}。

1 个答案:

答案 0 :(得分:2)

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