You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django ImproperlyConfigured错误求助:运行模型代码报错

问题:Django模型运行报错:settings未配置

我是编程新手,正在跟随《No Starch Python》教材学习Python,其中有Django相关章节,我按步骤编写了Topic模型代码,但运行后出现settings未配置的错误,以下是相关信息:

编写的Topic模型代码

from django.db import models

class Topic(models.Model):
    """A topic the user is learning about"""
    text = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        """Return a string representation of the model."""
        return self.text

运行后出现的错误信息

Traceback (most recent call last):
  File "/Users/admin/learning_log2/learning_logs/models.py", line 4, in <module>
    class Topic(models.Model):
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/models/base.py", line 127, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/registry.py", line 260, in get_containing_app_config
    self.check_apps_ready()
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/apps/registry.py", line 137, in check_apps_ready
    settings.INSTALLED_APPS
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/conf/__init__.py", line 92, in __getattr__
    self._setup(name)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/conf/__init__.py", line 72, in _setup
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

我的settings.py内容

"""
Django settings for learning_log project.

Generated by 'django-admin startproject' using Django 4.1.5.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-y8l9_wqzuq6#q@_0=f*$4-k_^o_enm3mmq+oe!*f*i-ktah(9w'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'learning_log.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'learning_log.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

我已尝试网上各种解决方案但均无效,也不理解问题的根本原因,请求告知问题原因及解决办法。我使用的是macOS High Sierra 10.13.6系统。


问题原因

这个错误的核心是你直接运行了models.py文件。Django模型是项目的组成部分,必须在项目的配置环境中才能被正确加载。单独运行模型文件时,Django无法找到项目的settings配置,因此抛出"settings未配置"的异常。另外,你的INSTALLED_APPS列表里还没有添加自己的app(learning_logs),这是后续操作必须补充的步骤,但直接运行模型文件是触发当前错误的直接原因。

解决办法

  • 不要直接运行models.py文件。Django模型需要通过Django命令行工具或shell来操作:
    1. 打开终端,进入项目根目录(包含manage.py的文件夹)
    2. 运行python manage.py shell,进入Django交互环境
    3. 在shell中导入模型:from learning_logs.models import Topic,之后即可测试模型功能
  • 将你的app添加到settings配置中:
    打开settings.py,在INSTALLED_APPS列表末尾添加'learning_logs',,保存后运行python manage.py makemigrations和python manage.py migrate命令,让Django识别并创建该app的模型表

内容的提问来源于stack exchange,提问作者James Huang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 09:27:41