我使用django 1.11,我试图通过引用此链接https://code.djangoproject.com/wiki/DynamicModels创建django动态模型,通过执行它没有任何问题运行的每一步,但我怎样才能看到这个创建的表在Django的管理面板?Django动态模型注册管理员
action.py
from django.db import models
from django.contrib import admin
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:
print admin_opts
class Admin(admin.ModelAdmin):
pass
for key, value in admin_opts:
setattr(Admin, key, value)
admin.site.register(model, Admin)
return model
在控制台:
from action import create_model
from django.db import models
fields = {
'first_name': models.CharField(max_length=255),
'last_name': models.CharField(max_length=255),
'__str__': lambda self: '%s %s' (self.first_name, self.last_name),
}
options = {
'ordering': ['last_name', 'first_name'],
'verbose_name': 'valued customer',
}
admin_opts = {}
model = create_model('Person', fields,
options=options,
admin_opts=admin_opts,
app_label='form',
module='project.app.model',
)
我看不出。通过
len(model._meta.fields)
但我没有,如何注册在管理员创建的模型的想法,田会出现什么参数里面admin_opts = {}
,我该怎么办makemigrations和迁移,我怎么能访问这个模型在views.py,从哪里我将导入这个模型。可以请你帮我这个,这对我和预先感谢非常有用。
感谢您的答复,但我使用最新的Django版本1.11,在这个'sql.sql_model_create'没有找到,我怎么能在1.11中实现这个? –
任何我如何创建表格,但是如何在管理员中注册?我厌倦了很多方法,但我无法做到这一点。你们能帮我解决这个问题吗?这对我来说是非常棒的。感谢advacne –
在views.py中有一个动态模型实例后,你是否尝试过这个“admin.site.register(model_name)”? –