Django Admin:如何在同一视图中显示来自两个不同模型的字段? [英] Django Admin: how to display fields from two different models in same view?
问题描述
我的站点使用 Django 的用户身份验证用户模型和自定义 UserProfile 模型来存储一些附加数据(生日等).有没有办法在 Django 管理中创建一个视图,将来自 User 和 UserProfile 模型的字段编织在一起?
My site makes use of Django's User Authentication User model and a custom UserProfile model to store some additional data (birthday, etc.). Is there a way to create a view in Django admin that weaves together fields from both the User and UserProfile models?
我怀疑这段代码片段甚至不接近,但也许它有助于说明我正在尝试做的事情:
I suspect that this code snippet is not even close, but maybe it will help illustrate what I'm trying to do:
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' 不是可调用的,也不是 'UserProfileAdmin' 的属性,也不是在模型 'UserProfile' 中找到.
ImproperlyConfigured: UserProfileAdmin.list_display[2], 'User.email' is not a callable or an attribute of 'UserProfileAdmin' or found in the model 'UserProfile'.
最终,我正在尝试创建一个管理视图,它首先具有 &UserProfile 中的姓氏和 User 中的电子邮件.
Ultimately, I'm trying to create an admin view that has first & last name from UserProfile and email from User.
推荐答案
为了显示用户电子邮件,您需要在 UserProfile
或 UserProfileAdmin
上有一个返回电子邮件的方法
for displaying user email you need to have a method on UserProfile
or UserProfileAdmin
that returns the email
在用户资料上
def user_email(self):
return self.user.email
或在 UserProfileAdmin 上
or on UserProfileAdmin
def user_email(self, instance):
return instance.user.email
然后将您的 list_display
更改为
list_display = ('name', 'gender', 'user_email')
这篇关于Django Admin:如何在同一视图中显示来自两个不同模型的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!