问题
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?
回答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()
回答2:
models created dynamically will not show up in the admin unless their
app_labelsmatch up with packages listed in INSTALLED_APPSThis 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
回答3:
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)
回答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.
来源:https://stackoverflow.com/questions/13184154/django-admin-registering-dynamic-model-from-action