views:

73

answers:

2

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.

+1  A: 

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(UserAdmin):
    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)
rebus
Thanks for the answer. Turns out that the one from Ashok was exactly what I needed, but I'm looking at this approach as well. Appreciate it.
Joe
Spent some time with this - it works, as well. Follow-up question: I can't seem to access some of the properties that are defined on UserProfile from the UserProfileInline. Is there a way to do this?
Joe
+2  A: 

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')
Ashok