【问题标题】:getting django.apps from shell but not script从 shell 获取 django.apps 但不是脚本
【发布时间】:2016-03-23 02:18:40
【问题描述】:

我可以在 shell 中获取我的应用信息:

In [1]: from django.apps import apps

In [2]: info = apps.all_models      

In [3]: for item in info:           
    print(item)
   ...:     
mailer
auth
analytics
subscribe
staticfiles
contenttypes
layout
contact

但不在脚本内。该脚本位于主站点文件夹中,即manage.py,而设置文件位于mysite/project/settings.py。脚本就在mysite,项目文件夹上方:

#!/usr/bin/env python
# coding: utf-8

import os, sys, subprocess, time, re, ast
# 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")

HOMEPATH = os.path.expanduser("~")

PROJECT_PATH = "{}/work_projects/mysite".format(HOMEPATH)

ENTRY_PATH = os.path.join(PROJECT_PATH, "project")

MOMMY_PATH = os.path.join(PROJECT_PATH, "model_mommy")

MOMMY_TESTPATH = os.path.join(MOMMY_PATH, "tests")

sys.path.append(ENTRY_PATH) 
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.project.settings")

from django.apps import apps

info = apps.all_models

for item in info:           
    print(item)

没有输出,信息为空白。导入django.conf.settings 并使用设置确实有效。为什么在这个脚本中做同样的事情不起作用?谢谢

【问题讨论】:

    标签: python django bash shell django-settings


    【解决方案1】:

    你可能错过了这个(我认为 mysite 不应该在设置行中):

    import os, sys
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
    import django
    django.setup()
    
    for item in django.apps.all_models:
        print(item)
    

    【讨论】:

      猜你喜欢
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-28
      • 2016-07-08
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多