简体   繁体   中英

django admin registering dynamic model from action

I have strange problem. In admin.py I can say:

admin.site.register(MyModel)

and this is obviously fine. Now I want this model to be loaded automatically as an result of user action:

def user_action_from_admin_panel(......):
    .....
    admin.site.register(MyModel)

MyModel class gets shows up in the admin as plain text without links. Any ideas to solve this?

May be you need this

from django.core.urlresolvers import clear_url_caches
from django.utils.importlib import import_module


def user_action_from_admin_panel(......):
    .....
    admin.site.register(MyModel)
    reload(import_module(settings.ROOT_URLCONF))
    clear_url_caches()

models created dynamically will not show up in the admin unless their app_labels match up with packages listed in INSTALLED_APPS

This is again by design, and should not be considered a bug.

Make sure you are adding app_label while creating a model

model = create_model('DynamicModel', app_label='existing_app')

Also reload your url conf so that new model gets links

# after creating model
from django.utils.importlib import import_module
reload(import_module(settings.ROOT_URLCONF))

Source: https://code.djangoproject.com/wiki/DynamicModels#Admininterface

I have black links if I don't permissions to add/change.

Try re-define your admin class:

class MyModelAdmin(admin.ModelAdmin):

    def has_add_permission(self, request):
        return True

    def has_change_permission(self, request):
        return True
...

admin.site.register(MyModel, MyModelAdmin)

The reason possibly is because Django couldn't find any URL match with that model for admin section. Hence, that model line in admin area will be set at disabled and no additional add or edit links.

For some cases, your code for registering models are triggered after the building of admin URLs ( django.contrib.admin.site.AdminSite.get_urls() ).A workaround solution is to update the whole admin urlpatterns of the global URLs, or using a Django apps named django-quickadmin , it will automatically load all custom models into admin without making any additional code.

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