在管理界面中显示用户组? [英] Display user group in admin interface?

查看:77
本文介绍了在管理界面中显示用户组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

contrib.auth上的admin.py定义了要在管理界面上为用户显示的字段:

The admin.py at contrib.auth defines the fields to be displayed for the user at the admin interface:

list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')

我想在这里查看每个用户的组:

I want to see the group of each user here:

仅出于测试目的,当您尝试添加组"字段时,它会失败:

Just for testing purpose when you try to add the "group" field it fail:

list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'group')

此错误上升::(admin.E109)'list_display [5]'的值不能为ManyToManyField.

This error rises: : (admin.E109) The value of 'list_display[5]' must not be a ManyToManyField.

搜索后,我发现只有将应用程序添加到管理界面或创建自定义用户模型的方法,但我认为我遗漏了一些东西.

After searching I have found only ways to add an app to the admin interface, or to create a custom user model, but I think I'm missing something.

那么,怎么做?

已解决 ---感谢@ {Alexis N-o}

SOLVED --- Thanks to the answer of @{Alexis N-o}

编辑/usr/local/lib/pyton2.7/dist-packages/django/contrib/auth/admin.py

Edit /usr/local/lib/pyton2.7/dist-packages/django/contrib/auth/admin.py

在list_display之前添加以下查找组的定义:

Just before the list_display add this def that seeks for the groups:

def group(self, user):
    groups = []
    for group in user.groups.all():
        groups.append(group.name)
    return ' '.join(groups)
group.short_description = 'Groups'

list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'group')

然后同步数据库,并在admin处检查更改,注意最后一列:

Then syncdb, and check the change at admin, notice the last column:

推荐答案

由于ManyToMany关系,默认情况下是不可能的,但这应该可行:

It is not possible by default because of the ManyToMany relation but this should work:

def group(self, user):
    groups = []
    for group in user.groups.all():
        groups.append(group.name)
    return ' '.join(groups)
group.short_description = 'Groups'

list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff', 'group')
# The last argument will display a column with the result of the "group" method defined above

您可以对其进行测试并整理代码以方便您使用.

You can test it and organize the code to your convenience.

这篇关于在管理界面中显示用户组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆