Python Can';t在脚本中导入django.apps
我有一个测试脚本:Python Can';t在脚本中导入django.apps,python,django,django-settings,django-apps,Python,Django,Django Settings,Django Apps,我有一个测试脚本: #!/usr/bin/env python # coding: utf-8 import os, sys, subprocess, time, re from django.conf import settings from django.apps import apps import django django.setup() """ http://stackoverflow.com/questions/24027901/dynamically-loading-dja
#!/usr/bin/env python
# coding: utf-8
import os, sys, subprocess, time, re
from django.conf import settings
from django.apps import apps
import django
django.setup()
"""
http://stackoverflow.com/questions/24027901/dynamically-loading-django-apps-at-runtime
"""
MAIN_IMPORTS = """\
from django.test import TestCase
from model_mommy import mommy
"""
IMPORT_STATEMENT = """\
from clientsite.{app}.models import {models}
"""
TEST_BLOCK = """\
class {modelname}CreationTests(TestCase):
def setUp(self):
self.model = {modelname}
def test_create(self):
x = mommy.make(self.model)
x.save()
self.assertTrue(x.pk)
def test_factory_isinstance(self):
x = mommy.make(self.model)
self.assertTrue(isinstance(x, {modelname}))
"""
all_apps = apps.get_apps()
all_models = apps.get_models()
model_info = apps.all_models
我希望能够在脚本中使用django.apps
。脚本在一个应用程序中,比如mysite/mommy\u app/scripts/testtasm.py
我试过了
cchilders:~/work_projects/mysite [ckc/fixture-replacements]$ ./manage.py mysite/mommy_models/scripts/testtasm.py
Unknown command: 'mysite/mommy_models/scripts/testtasm.py'
结果失败了
django.setup()
也失败
如何在脚本中使用django功能而不实际运行runserver?谢谢。除非您已经创建了 您应该使用
python mysite/mommy_models/scripts/testtasm.py
或者,如果脚本是可执行的
mysite/mommy_models/scripts/testtasm.py
在脚本中,在调用django.setup
之前,必须设置django\u SETTINGS\u模块
环境变量。您可能还必须将项目目录添加到Python路径
import os
import sys
# This should be the directory that contains the directory containing settings.py
sys.path.add('/path/to/mysite')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
django.setup()
# now you can import the settings and access them
from django.conf import settings
您是否尝试过将其作为普通python脚本运行?