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

请求解决Django ImproperlyConfigured配置错误问题

Django ImproperlyConfigured 错误排查与解决

错误信息

django.core.exceptions.ImproperlyConfigured: 请求获取DEBUG配置项,但尚未配置设置。您必须在访问设置前定义环境变量DJANGO_SETTINGS_MODULE或调用settings.configure()。

用户提供的代码

manage.py

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'alumni_portal.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()

settings.py

import os
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
BASE_DIR2 = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR2,'templates')
STATIC_DIR = os.path.join(BASE_DIR2, 'static')


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-nj@^0^n%be!u=8!o5ui7efi*b7)iad2(jgw06^flv=z4i$z%7_'

# 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',
    'portal',
    'ckeditor',
    'ckeditor_uploader',
    'crispy_forms',
    'django_social_share',
    'import_export',
]

# CKEDITOR_UPLOADER_PATH = 'media/'

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 = 'alumni_portal.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'templates')],
        '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 = 'alumni_portal.wsgi.application'


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'dbs',
        'HOST': '127.0.0.2',
        'PORT': '3300',
        'USER': 'root',
        'PASSWORD': '*********',
        'OPTIONS': {
        'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
        'init_command': "set FOREIGN_KEY_CHECKS = 0;",

        }
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.0/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.0/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.0/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    STATIC_DIR
]

STATIC_ROOT = os.path.join(BASE_DIR, "/static")

MEDIA_URL = '/uploads/'
MEDIA_ROOT = os.path.join(BASE_DIR2, 'uploads')
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

AUTH_USER_MODEL = 'portal.User'
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

LOGIN_REDIRECT_URL = 'dashboard'

CRISPY_TEMPLATE_PACK = 'bootstrap4'
CKEDITOR_UPLOAD_PATH = "uploads/"
CKEDITOR_CONFIGS = {
    'default': {
        'height': '100%', 
        'width': '100%', 
    },
}

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_USE_TLS = True
EMAIL_PORT = 587

解决步骤

  • 确保在项目根目录运行命令:必须在包含manage.py的目录下执行python manage.py相关命令,路径错误会导致Django找不到settings模块。
  • 验证项目结构:确认alumni_portal目录与manage.py同级,且settings.py在该目录内,对应DJANGO_SETTINGS_MODULE设置的alumni_portal.settings路径。
  • 修复STATIC_ROOT路径:将settings.py中的STATIC_ROOT = os.path.join(BASE_DIR, "/static")改为STATIC_ROOT = os.path.join(BASE_DIR, "static"),避免绝对路径拼接错误。
  • 检查提前导入settings的代码:如果项目中存在模块级别的from django.conf import settings导入(比如在models、views的顶部),会在Django初始化前触发配置读取,需将这类代码移到函数内部执行。
  • 指定settings模块运行:若以上方法无效,可手动指定settings模块运行命令:
    python manage.py runserver --settings=alumni_portal.settings
    
  • 确认虚拟环境状态:激活项目对应的虚拟环境,确保Django安装在该环境中,避免版本或路径冲突。

内容的提问来源于stack exchange,提问作者Tariq Jamal A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 17:40:29