Django 管理员 : how to display fields from two different models in same view?

标签 django django-models django-admin

我的站点使用 Django 的用户身份验证用户模型和自定义 UserProfile 模型来存储一些附加数据(生日等)。有没有办法在 Django 管理中创建一个 View ,将 User 和 UserProfile 模型的字段编织在一起?

我怀疑这个代码片段还不够接近,但它可能有助于说明我正在尝试做的事情:

from django.contrib import admin
from django.contrib.auth.models import User
from userprofile.models import UserProfile


class UserProfileAdmin(admin.ModelAdmin):
    list_display = ('name', 'gender', 'User.email') #user.email creates the error - tried some variations here, but no luck.

admin.site.register(UserProfile, UserProfileAdmin)

错误信息:

ImproperlyConfigured: UserProfileAdmin.list_display[2], 'User.email' is not a callable or an attribute of 'UserProfileAdmin' or found in the model 'UserProfile'.

最终,我尝试创建一个管理 View ,该 View 具有来自 UserProfile 的名字和姓氏以及来自用户的电子邮件。

最佳答案

要显示用户电子邮件,您需要在 UserProfileUserProfileAdmin 上有一个返回电子邮件的方法

在用户文件上

def user_email(self):
    return self.user.email

或在 UserProfileAdmin 上

def user_email(self, instance):
    return instance.user.email

然后将您的 list_display 更改为

list_display = ('name', 'gender', 'user_email')

相关文档:ModelAdmin.list_display

关于Django 管理员 : how to display fields from two different models in same view?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3409970/

相关文章:

django - 模板不存在

django - 自定义 Django 管理模板

django - 我将如何在 Django 中执行此查询?

python - 在 Django 中使用电子邮件和密码登录

django - 如何在django中没有模型的情况下从数据库中获取数据?

python - 管理员内联中的django自定义字段

mysql - 显示 django admin 中另一个模型中的记录

django - 上下文处理器无法与 Django 中的 Jinja2 一起使用

python - django 如何全局使用变量

python - 如何在 Django 管理中测试覆盖函数?