在admin.StackedInline内联中访问模型对象 [英] Access model object in admin.StackedInline inline

查看:561
本文介绍了在admin.StackedInline内联中访问模型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 admin.py中的 UserAdmin 中使用内联 code>
我正在寻找一种基于对象修改该 inline 的字段的方法。

I am trying to use an inline in UserAdmin in admin.py I am looking for a way to modify the fields of that inline based on the object.

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



UserAdmin

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

这里我需要修改 ProfileInline.fields =('部门','email_role')如果用户属于销售 分组,否则。

Here I need to modify ProfileInline.fields = ('department','email_role') if the user belongs to the Sales Group, else whatever.

我需要一种访问用户对象并更新字段的方法。

I need a way to access the user Object and update the fields.

推荐答案

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

get_fieldsets method is your solution. You have request object so request.user also.

这篇关于在admin.StackedInline内联中访问模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆