Skip to content Skip to sidebar Skip to footer

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 actio

Solution 1:

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()

Solution 2:

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 modelfrom django.utils.importlib import import_module
reload(import_module(settings.ROOT_URLCONF))

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

Solution 3:

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

Try re-define your admin class:

classMyModelAdmin(admin.ModelAdmin):

    defhas_add_permission(self, request):
        returnTruedefhas_change_permission(self, request):
        returnTrue
...

admin.site.register(MyModel, MyModelAdmin)

Solution 4:

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.

Post a Comment for "Django Admin Registering Dynamic Model From Action"