2

I'm following a tutorial for the Django admin app and I'm trying a step in which the default admin site is replaced with a custom subclass of AdminSite from django.contrib.admin.

My project structure is:

MyAdminTutorial
|- MyAdminTutorial
|- MyActualApp
|- JustAUserApp

MyActualApp.admin.py:

[...other imports]
from django.contrib.auth.admin import UserAdmin, GroupAdmin

class MyAdminSite(admin.AdminSite):
    pass

admin.site = MyAdminSite()

admin.site.register(User, UserAdmin)
admin.site.register(Group, GroupAdmin)

MyActualApp.apps.py:

from django.contrib.admin.apps import AdminConfig

class MyAdminConfig(AdminConfig):
    default_site = 'MyActualApp.admin.MyAdminSite'

MyAdminTutorial.settings.py

INSTALLED_APPS = [
    "MyActualApp.apps.MyAdminConfig",
    # 'django.contrib.admin',
    ....
    "JustAUserApp",
]

If I try to run the development server I get this error:

ImportError: Module "MyActualApp.admin" does not define a "MyAdminSite" attribute/class

Messing around in the debugger i found the error stems from a call to getattr() inside import_string() in django.utils.module_loading.py.

For the current call to import_string() the module name and path are set to MyActualApp.admin, getting the current location in the debug console yields the main MyActualApp directory (the project's), but calling getattr(module, "MyAdminSite") triggers the error above.

I expect the MyAdminSite class to be found, but that's not the case, what is going on in this project, what further checks am I not considering?

maja
  • 697
  • 5
  • 18

1 Answers1

0

It turns out that the line which imports UserAdmin and GroupAdmin from django.contrib.auth.admin must be placed after the declaration of whatever classes I want to declare in admin.py. So that the code looks like this:

[...other imports]

class MyAdminSite(admin.AdminSite):
    pass

admin.site = MyAdminSite()

from django.contrib.auth.admin import UserAdmin, GroupAdmin

admin.site.register(User, UserAdmin)
admin.site.register(Group, GroupAdmin)

The code works if modified like this, but I'll leave the question unanswered because I have no idea of what is actually going on.

maja
  • 697
  • 5
  • 18