django.core.exceptions.ImproperlyConfigured:请求设置LOGGING_CONFIG,但未配置设置

Ski*_*345 13 python django

我正在尝试运行一个填充脚本,我将它放在tango_with_django教程(https://github.com/leifos/tango_with_django/blob/master/tango_with_django_project/populate_rango.py)中,但是我得到了下面的回溯并且它似乎与Django 1.7中的变化有关?如果有人能解释我在这里做错了什么,我会很感激.

(test_env) C:\Users\WriteCode\test_env\epl>python populate_clubs.py
Traceback (most recent call last):
  File "populate_clubs.py", line 4, in <module>
    django.setup()
  File "c:\Python27\lib\site-packages\django\__init__.py", line 20, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "c:\Python27\lib\site-packages\django\conf\__init__.py", line 46, in __ge
tattr__
    self._setup(name)
  File "c:\Python27\lib\site-packages\django\conf\__init__.py", line 40, in _set
up
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, b
ut settings are not configured. You must either define the environment variable
DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

(test_env) C:\Users\WriteCode\test_env\epl>
Run Code Online (Sandbox Code Playgroud)

我的populate_clubs.py脚本

import os
import sys
import django
django.setup()


def add_club(name, nickname, manager, established, stadium, active=True):
    c = clubs.objects.get_or_create(name=name, nickname=nickname, manager=manager, established=established, stadium=stadium, active=active)
    return c

def populate():
    add_club(name = "Aston Villa",
        nickname = "Villans",
        manager = "Tim Sherwood",
        established = "1897",
        stadium = "Villa Park"
        )

    # Print out what was added
    for c in clubs.objects.all():
        print "The following has been added to clubs:" + c



# Start execution
if __name__ == '__main__':
    print "Starting club population script..."
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'epl.settings')
    from teams.models import clubs
    populate()
Run Code Online (Sandbox Code Playgroud)

bwa*_*gel 20

你可以在行os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")之前插入django.setup().

  • 在`PyCharm - >设置 - >构建,执行,部署 - >控制台 - > Django控制台`中有一个专用按钮来设置`环境变量`.打开它并添加`DJANGO_SETTINGS_MODULE` =`some_project.settings` (6认同)
  • 我在使用PyCharm(2017.2.3版本)作为我的IDE时遇到了同样的问题。要解决此问题,请转到“ PyCharm-&gt;设置-&gt;构建,执行,部署-&gt;控制台-&gt; Django控制台”。然后在“启动脚本”窗口中输入“ os.environ.setdefault(...)”。 (2认同)

Gwy*_*idD 11

调用后django.setup应该设置DJANGO_SETTINGS_MODULE环境变量.然后把它移到__main__右边os.environ.setdefault.

  • 这该怎么做 ? (7认同)

Edw*_*ett 10

如果在通过python在终端中运行启动与Django的交互后遇到类似的错误,则python manage.py shell在相应的目录中运行可能会解决您的问题.