I'm using Django 1.11 and I tried to create Django dynamic models by referring this link https://code.djangoproject.com/wiki/DynamicModels, by executing each and every step it runs without any issue, but when I see the registered model in the Django admin panel, the Model is visible under it corresponding app, but it not accessible, I don't know what I missed out there.
def create_model(name, fields=None, app_label='', module='', options=None, admin_opts=None):
"""
Create specified model
"""
class Meta:
# Using type('Meta', ...) gives a dictproxy error during model creation
pass
if app_label:
# app_label must be set using the Meta inner class
setattr(Meta, 'app_label', app_label)
# Update Meta with any options that were provided
if options is not None:
for key, value in options.iteritems():
setattr(Meta, key, value)
# Set up a dictionary to simulate declarations within a class
attrs = {'__module__': module, 'Meta': Meta}
# Add in any fields that were provided
if fields:
attrs.update(fields)
# Create the class, which automatically triggers ModelBase processing
model = type(name, (models.Model,), attrs)
# Create an Admin class if admin options were provided
if admin_opts is not None:
class Admin(admin.ModelAdmin):
pass
for key, value in admin_opts:
setattr(Admin, key, value)
admin.site.register(model, Admin)
return model
Please refer this image for reference:
Here the model Test 11 is created by dynamic model method, I am not able to access that model, Add/Change Button also not there and when I kill the server and restart it , that dynamically created model gets hide.
How can I access this model? Did I miss any steps here or what's wrong in it?
I had the same issue, but a few lines of code solved it. You are going to need to register your dynamic models and then reload and clear your cache. It will look something like this:
from django.contrib import admin
from django.core.urlresolvers import clear_url_caches
from django.utils.module_loading import import_module
admin.site.register(model, admin_options)
reload(import_module(settings.ROOT_URLCONF))
clear_url_caches()