Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

Django Admin: how to display fields from two different models in same view?

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)

Error message:

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

Ultimately, I'm trying to create an admin view that has first & last name from UserProfile and email from User.

question from:https://stackoverflow.com/questions/3409970/django-admin-how-to-display-fields-from-two-different-models-in-same-view

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

for displaying user email you need to have a method on UserProfile or UserProfileAdmin that returns the email

on UserProfile

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

or on UserProfileAdmin

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

then change your list_display to

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

Related docs: ModelAdmin.list_display


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...