简体   繁体   中英

Defning Django admin models inside subdirectories instead of admin.py

My goal is to define admin models in separate files. So the project structure looks like this:

app

admin_models
       __init__.py
       TestAdmin.py

TestAdmin.py:

from django.contrib import admin
from cms.models import (
    TestModel)


class TestAdmin(admin.ModelAdmin):
    fields = (...)


admin.site.register(TestModel, TestAdmin)

The problem is that the model does not appear on the admin page. However, in standard structure (if I move TestAdmin.py file's content to admin.py on the top level inside the app) then everything works fine. Anyway to fix this?

Django's internals (eg the "autodiscovery" ) rely on a certain app structure. Part of that is that the admin namespace within an installed app is imported at app loading time (in the AppConfig.ready method). So you can make a package structure like:

app
    admin
        __init__.py
        test_admin.py  # different from admin class name!
        another_admin.py

In your test_admin.py you define your TestAdmin class as you have before. And in the package's __init__.py , you import the admins from the submodules:

# __init__.py
from .test_admin import TestAdmin
from .other_admin import YetAnotherAdmin

That way, you can structure your code base and django's internal working will still register the model admins as they are in the place where it's looking for them.

As pointed out by @Alasdair, you can also "manually" import your custom admin modules in a custom AppConfig. If you don't already have one, I would stick with the above described method as it doesn't require changes in various places ( INSTALLED_APPS or app/__init__.py , app/apps.py , ...) that could have unforeseen side effects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM