user2035177 user2035177 - 4 months ago 15
Python Question

How to show a Django auth user field in a custom admin list display

I am using the Django auth user model along with a custom user profile model. The user profile admin looks like this:

class UserProfileAdmin(admin.ModelAdmin):
list_display = ['user', 'first_login', 'project', 'type']
class Meta:
model = UserProfile


The user profile model looks like this:

class UserProfile(models.Model):
user = models.OneToOneField(User)
first_login = models.BooleanField(default = True)
TYPE_CHOICES = (('R', 'Reader'), ('A', 'Author'))
type = models.CharField(max_length = 9, choices = TYP_CHOICES, blank = True)
project = models.ForeignKey('Project', on_delete=models.CASCADE)


What I like to do is to display the
is_active
property of the user in the list display of the UserProfileAdmin. Is this possible, and if yes, how?

Answer

It is possible if you define say wrapped_is_active method in your custom admin model with signature like:

def wrapped_is_active(self, item):
    if item:
        return item.user.is_active
wrapped_is_active.boolean = True

You should specify that method in your list_display, so that is becomes like:

list_display=['user', 'first_login', 'project', 'type', 'wrapped_is_active']

for more information see Django admin site documentation