0

我通过 Django 将 MySQL 数据库连接到项目。在settings.py文件中,我规定了以下内容:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydb',
        'USER': 'root',
        'PASSWORD': '1',
    }
}

接下来,为了测试配置,我执行以下命令:

>>> from django.db import connection
>>> cursor = connection.cursor()

控制台给了我以下信息:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/django/db/__init__.py", line 11, in <module>
    if settings.DATABASES and DEFAULT_DB_ALIAS not in settings.DATABASES:
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 53, in __getattr__
    self._setup(name)
  File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 46, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

请帮帮我。我最近开始学习 Django。

4

3 回答 3

1

您收到错误的原因是您需要加载 django 的设置才能使用 django 的配置、模型和工具。django 提供了shell管理命令,它将加载为 django 配置的 Python 提示符。

python manage.py shell从你的项目目录(不是你的应用程序)运行,然后你不会得到那个错误(你会得到一个不同的错误)。

在学习 django 时,不要使用 MySQL 作为数据库。按照教程中的建议,使用内置的 sqlite 数据库来加快 django 的速度。

于 2013-09-28T18:23:11.290 回答
0

settings.py没有HOSTPORT

于 2013-09-28T18:27:17.457 回答
0

如果你看看你的数据库配置:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydb',
        'USER': 'root',
        'PASSWORD': '1',
    }
}

您尚未设置HOSTPORT。由于您的错误状态(没有所有必需的键及其各自的值将导致 django 抛出错误。在这种情况下,HOST并且PORT是要求):

django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

如果您在 localhost 上进行开发,那么您HOST应该''和您的PORT应该是3306MySQL 的默认设置(除非您在安装过程中更改了此设置)。

如果您是 django 新手,请尝试使用 SQLite,因为它最容易上手。但是如果你选择使用 SQLite,那么你必须在NAME. .db如果您还没有创建 SQLite文件,请不要担心。如果没有退出,它将为您创建一个。

于 2013-09-28T18:28:08.223 回答