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

46👍

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

👤Ashok

17👍

You could try using InlineModelAdmin to display both User and UserPofile forms in a admin view.

To display user profile information in change list you can create a new method that delegates the values from UserProfile to User model.

For example this should work more or less 🙂

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

from my_models import UserProfile

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    fk_name = 'user'

class UserAdmin(admin.ModelAdmin):
    list_display = ['get_userprofile_name', 'email']
    list_select_related = True
    inlines = [
        UserProfileInline,
    ]

    def get_userprofile_name(self, instance):
        # instance is User instance
        return instance.get_profile().name

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

1👍

Using Ashoks top answer i made snippet that simplifies this process for large number of fields

class ColumnViewer(object):
    pass

column_list = ('name', 'surname', )

for col in column_list:
    setattr(ColumnViewer, col, lambda s,i : getattr(i, col))

@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin, ColumnViewer):
    list_display = column_list

Leave a comment