简体   繁体   English

在子目录中定义 Django 管理模型而不是 admin.py

[英]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:测试管理员.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.问题是 model 没有出现在管理页面上。 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.但是,在标准结构中(如果我将TestAdmin.py文件的内容移动到应用程序内部顶层的admin.py ),那么一切正常。 Anyway to fix this?有任何解决这个问题的方法吗?

Django's internals (eg the "autodiscovery" ) rely on a certain app structure. Django 的内部结构(例如“自动发现” )依赖于特定的应用程序结构。 Part of that is that the admin namespace within an installed app is imported at app loading time (in the AppConfig.ready method).部分原因是已安装应用程序中的admin命名空间是在应用程序加载时导入的(在AppConfig.ready方法中)。 So you can make a package structure like:所以你可以制作一个 package 结构,如:

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.在您的test_admin.py中,您像以前一样定义您的TestAdmin class。 And in the package's __init__.py , you import the admins from the submodules:在包的__init__.py中,您从子模块中导入管理员:

# __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.这样,您可以构建您的代码库,django 的内部工作仍将注册 model 管理员,因为他们在寻找它们的地方。

As pointed out by @Alasdair, you can also "manually" import your custom admin modules in a custom AppConfig.正如@Alasdair 所指出的,您还可以在自定义 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.如果您还没有,我会坚持使用上述方法,因为它不需要在各个地方进行更改( INSTALLED_APPSapp/__init__.pyapp/apps.py ,...),这可能是无法预料的副作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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