我的站点使用 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 的名字和姓氏以及来自用户的电子邮件。
最佳答案
要显示用户电子邮件,您需要在 UserProfile
或 UserProfileAdmin
上有一个返回电子邮件的方法
在用户文件上
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')
关于Django 管理员 : how to display fields from two different models in same view?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3409970/