Search code examples
pythondjangodjango-admin

Adding django import_export to Abstract User Model


Below is my admin.py file.

I want to implement the import_export feature on the Employee model which is Abstract User Model.

from django.contrib import admin
from inventory.models import Employee
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Group
from import_export.admin import ImportExportModelAdmin
admin.site.unregister(Group)

# admin.site.register(Employee)


class EmployeeAdmin(UserAdmin):
    list_display = ('emp_num', 'emp_name', 'email',
                    'emp_designation', 'is_admin', 'is_staff')
    search_fields = ('emp_num', 'emp_name')

    readonly_fields = ('last_login',)
    ordering = ('emp_num',)
    filter_horizontal = ()
    list_filter = ('is_admin',)
    fieldsets = ()


admin.site.register(Employee, EmployeeAdmin)

Solution

  • The ImportExportModelAdmin [readthedocs.io] is just a ModelAdmin with a ImportExportMixin [readthedocs.io], so probably the most clean solution is use the ImportExportMixin:

    from django.contrib import admin
    from inventory.models import Employee
    from django.contrib.auth.admin import UserAdmin
    from django.contrib.auth.models import Group
    from import_export.admin import ImportExportMixin
    admin.site.unregister(Group)
    
    # admin.site.register(Employee)
    
    
    class EmployeeAdmin(ImportExportMixin, UserAdmin):
        list_display = ('emp_num', 'emp_name', 'email',
                        'emp_designation', 'is_admin', 'is_staff')
        search_fields = ('emp_num', 'emp_name')
    
        readonly_fields = ('last_login',)
        ordering = ('emp_num',)
        filter_horizontal = ()
        list_filter = ('is_admin',)
        fieldsets = ()
    
    
    admin.site.register(Employee, EmployeeAdmin)