django xadmin问题记录

python  :  3.5.2
django  :  2.0.5

1、安装
如果直接pip安装,安装的xadmin是python2的,因此需要从github安装:

pip install https://codeload.github.com/sshwsfc/xadmin/zip/django2

2、修改xadmin后台的User模型样式
xadmin自身已经将User模型注册了,所以如果需要修改User模型在xadmin后台的样式,继承原有的类再做修改即可。以下是原有的类的源代码:

class UserAdmin(object):
    change_user_password_template = None
    list_display = ('username', 'email', 'first_name', 'last_name', 'is_staff')
    list_filter = ('is_staff', 'is_superuser', 'is_active')
    search_fields = ('username', 'first_name', 'last_name', 'email')
    ordering = ('username',)
    style_fields = {'user_permissions': 'm2m_transfer'}
    model_icon = 'fa fa-user'
    relfield_style = 'fk-ajax'

    def get_field_attrs(self, db_field, **kwargs):
        attrs = super(UserAdmin, self).get_field_attrs(db_field, **kwargs)
        if db_field.name == 'user_permissions':
            attrs['form_class'] = PermissionModelMultipleChoiceField
        return attrs

    def get_model_form(self, **kwargs):
        if self.org_obj is None:
            self.form = UserCreationForm
        else:
            self.form = UserChangeForm
        return super(UserAdmin, self).get_model_form(**kwargs)

    def get_form_layout(self):
        if self.org_obj:
            self.form_layout = (
                Main(
                    Fieldset('',
                             'username', 'password',
                             css_class='unsort no_title'
                             ),
                    Fieldset(_('Personal info'),
                             Row('first_name', 'last_name'),
                             'email'
                             ),
                    Fieldset(_('Permissions'),
                             'groups', 'user_permissions'
                             ),
                    Fieldset(_('Important dates'),
                             'last_login', 'date_joined'
                             ),
                ),
                Side(
                    Fieldset(_('Status'),
                             'is_active', 'is_staff', 'is_superuser',
                             ),
                )
            )
        return super(UserAdmin, self).get_form_layout()

在自己的xadmin.py文件中继承并修改:

import xadmin
from xadmin.plugins.auth import UserAdmin as XadminUserAdmin

class UserAdmin(XadminUserAdmin):
    '''
    修改自己的样式
    '''
    list_display = ('username', 'id', 'email', 'is_staff', 'is_superuser', 'is_active')
    

# 需要将已经注册的User注销,再重新用自己定义的UserAdmin再注册一次
xadmin.site.unregister(User)
xadmin.site.register(User, UserAdmin)
Show Comments