Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 974
Joe Avatar asked Aug 04 '10 21:08

Joe


People also ask

How to edit multiple models from one Django admin?

To be able to edit multiple objects from one Django admin, you need to use inlines. You can see the form to add and edit Villain inside the Category admin. If the Inline model has alot of fields, use StackedInline else use TabularInline .

What is__ str__ in Django?

The __str__ method in Python represents the class objects as a string – it can be used for classes. The __str__ method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.

What is get_ absolute_ url in Django?

get_absolute_url allows to keep your object DRY. To have a url which defines that object instance. In most case a detail page for that object.


1 Answers

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

like image 195
Ashok Avatar answered Oct 09 '22 09:10

Ashok