Auto register Django auth models using custom admin site

后端 未结 4 1007
轻奢々
轻奢々 2020-12-29 06:35

I implemented authentication management using Django auth with the default admin site but then I wanted to use my own AdminSite to rewrite some behaviors:

cl         


        
4条回答
  •  猫巷女王i
    2020-12-29 06:59

    The Django docs suggest using SimpleAdminConfig with a custom admin site.

    INSTALLED_APPS = (
        ...
        'django.contrib.admin.apps.SimpleAdminConfig',
        ...
    )
    

    That prevents the models being registered with the default AdminSite.

    The docs seem to assume that you will import the models individually and add them to your custom admin site:

    from django.contrib.auth.models import Group, User
    from django.contrib.auth.admin import GroupAdmin, UserAdmin
    
    admin_site.register(Group, GroupAdmin)
    admin_site.register(User, UserAdmin)
    

    This would be very repetitive if you have models in many apps. It doesn't offer any advice how to automatically register models from all your apps with your custom site.

    You could try monkey patching admin, and replacing admin.site with your own.

    from django.contrib import admin
    admin.site = OptiAdmin(name='opti_admin')
    

    Then, when code called admin.site.register(), it would register the model with your admin site. This code would have to run before any models were registered. You could try putting it in the AppConfig for your app, and make sure that your app is above django.contrib.admin.

提交回复
热议问题