我生成Django模型動態我的應用程序過程中從YAML描述文件中啓動。我在django管理員註冊他們,但他們在管理界面顯示禁用。看起來像this。爲什麼我的模型顯示在Django管理禁用?
我創建manage.py命令以YAML格式動態地創建描述文件的模型。
from django.core.management.base import BaseCommand
from django.core.management import call_command
import yaml
from generation.generate import generate_fields, generate_model
class Command(BaseCommand):
help = 'Generates or updates django models from specified file'
def handle(self, *args, **options):
try:
f = open(args[0], 'r')
models = yaml.safe_load(f)
f.close()
for name, definition in models.items():
fields = generate_fields(definition['fields'])
generate_model(name, definition['title'], fields, "generation", "generation.models")
call_command('syncdb', interactive=True)
except IOError:
self.stderr.write('Cannot open file: {0}'.format(args[0]))
except yaml.YAMLError as e:
self.stderr.write('Cannot parse file {0}: {1}'.format(args[0], e))
我從根urls.py啓動這個命令是這樣的:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from generation import views
from generation.management.commands.updatemodels import Command
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', views.main, name='main'),
# url(r'^modgen/', include('modgen.foo.urls')),
url(r'^admin/', include(admin.site.urls)),
)
Command().handle('models.yaml')
我生成模型,並以這種方式在管理註冊:
from sys import stderr
from django.contrib import admin
from django.db import models
class Types():
INT = 'int'
CHAR = 'char'
DATE = 'date'
def generate_model(model_name, model_title, fields, app_label, module):
class Meta:
pass
if app_label:
setattr(Meta, 'app_label', app_label)
if model_title:
setattr(Meta, 'verbose_name_plural', model_title)
attrs = {'__module__': module, 'Meta': Meta}
if fields is not None:
attrs = dict(attrs.items() + fields.items())
model = type(model_name, (models.Model,), attrs)
admin.site.register(model)
def generate_fields(definition):
fields = {}
for field in definition:
fields[field['id']] = generate_field(field['title'], field['type'])
return fields
def generate_field(title, field_type):
if field_type == Types.CHAR:
return models.CharField(title, max_length=255)
elif field_type == Types.INT:
return models.IntegerField(title)
elif field_type == Types.DATE:
return models.DateField(title)
else:
stderr.write('Unknown field type specified: {0}'.format(field_type))
爲什麼模特展示了殘疾人在管理界面? Django成功註冊它們。
還有一個類似的問題這裏:[Django管理登記從動作動態模型(http://stackoverflow.com/questions/13184154/django-admin-registering-dynamic-model-from-action) 。但它也沒有解決。 – Yuriy 2013-04-08 05:41:56