如何在自定义管理列表中显示Django auth用户字段显示

问题描述:

我正在使用Django auth用户模型以及自定义用户配置文件模型。用户配置文件管理是这样的:如何在自定义管理列表中显示Django auth用户字段显示

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

用户配置文件模型是这样的:

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) 

我喜欢做的是在该列表显示中显示用户的is_active财产UserProfileAdmin。这是可能的,如果是的话,如何?

这是可能的,如果你定义说wrapped_is_active方法与类似签名的自定义管理模式:

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

就应该在你的list_display该方法,所以这就是变得像:

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

欲了解更多信息,请参阅Django admin site documentation

+0

工作:)但为什么查找不起作用,如'user__is_active'? –

+0

我不确定,但是在这种情况下,admin似乎基于'queryset'数据构建了他们的视图。并检查属性,如果是可调用的,则调用它来获取值。可以用admin的'get_queryset'方法来玩。但绝对应该重复检查。 –

+0

有一张票[#5863](https://code.djangoproject.com/ticket/5863)允许'list_display'处理像'user__is_active'这样的外键的属性,但它被关闭为“不会修复”。 – Alasdair

有可能:我在您的代码中进行了更改:

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


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) 
is_active = models.BooleanField(default=True)