【问题标题】:How to make visible a ManyToManyField from UserProfile in User admin tab (Django-Admin)如何在用户管理选项卡(Django-Admin)中的 UserProfile 中显示 ManyToManyField
【发布时间】:2016-04-08 20:31:11
【问题描述】:

如何使UserProfileManyToMany 属性(其属性user = OneToOne(User)Django-Admin 中可见?

所以有一个常见的User 模型用于登录/注册。这个User 模型通过在UserProfile 模型中使用OneToOneField(User,related_name='userprofile') 进行了扩展。

UserProfile 具有ManyToManyField 属性:

languages = models.ManyToManyField(Language, through='UserProfileLanguage')

这就是问题所在。

我在Django-AdminUser 选项卡中看不到languages。 我可以在User 选项卡中看到所有UserProfile 属性,因为我这样做了:

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    can_delete = False
    verbose_name_plural = 'User_Profile'

class UserAdmin(BaseUserAdmin):
    inlines = (UserProfileInline, )

但我在User 选项卡中看不到的UserProfile 的唯一属性是languages。我读过这可能是因为它是ManyToManyField,但我不知道如何将它放在User 选项卡中。

我试图把它作为一个内联模型,但它引发了错误:

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    can_delete = False
    verbose_name_plural = 'User_Profile'

class UserProfileLanguageLevelInline(admin.TabularInline):
    model = UserProfileLanguage
    # THIS DOES NOT WORK EITHER: model = User.userprofile.languages.through

class UserAdmin(BaseUserAdmin):
    inlines = (UserProfileInline, UserProfileLanguageLevelInline)

<class 'SolutionsForLanguagesApp.admin.UserProfileLanguageLevelInline'>: (admin.
E202) 'SolutionsForLanguagesApp.UserProfileLanguage' has no ForeignKey to 'auth.
User'.

这是因为languagesUserProfile 的属性,而不是User,但我不知道如何解决。

【问题讨论】:

    标签: python django django-models django-admin


    【解决方案1】:

    在您的情况下,如果您可以看到languages 但不能编辑User 选项卡中的字段,则应使用readonly_fields

    class UserProfileInline(admin.StackedInline):
        model = UserProfile
        can_delete = False
        verbose_name_plural = 'User_Profile'
        readonly_fields = ('languages',)
    
    class UserAdmin(BaseUserAdmin):
        inlines = (UserProfileInline, )
    

    【讨论】:

    • 谢谢哈维尔,如果我能更改语言和级别,那就最好不过了。这可以使其在 Userprofile 选项卡中工作,但不能以这种方式在 User 选项卡中工作。你知道该怎么做吗?非常感谢
    • 我阐述了我的想法,在您的第一个示例中,原因是through='UserProfileLanguage' 创建了一个中间表app_userprofile_languages,它更容易进行 ORM 过滤,但无法理解为什么数据不暴露或不暴露有任何警告。所以如果你不使用through,你可以看到languages。在第二个示例中,当您 admin.site.register(User, UserAdmin) 模型 UserProfileLanguage 没有对 User 的 FK 并且您确实显示了该表中的字段时。我希望得到解释,如果其他人可以帮助理解这一点。
    猜你喜欢
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 2010-09-14
    相关资源
    最近更新 更多