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

Django迁移PostgreSQL遇ModuleNotFoundError及importlib问题求助

Django迁移PostgreSQL报错修复方案

问题背景

尝试将Django模型迁移到PostgreSQL数据库时触发错误,核心报错为ModuleNotFoundError: No module named 'threeapp.apps.threeappConfig'; 'threeapp.apps' is not a package,伴随importlib相关加载异常。

报错信息

File "C:\Program Files\Python311\Lib\threading.py", line 1039, in _bootstrap_inner
    self.run()
  File "C:\Program Files\Python311\Lib\threading.py", line 976, in run
    self._target(*self._args, **self._kwargs)
  File "J:\good\test\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args,**kwargs)
  File "J:\good\test\Lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run
    autoreload.raise_last_exception()
  File "J:\good\test\Lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception
    raise _exception[1]
  File "J:\good\test\Lib\site-packages\django\core\management\__init__.py", line 394, in execute
    autoreload.check_errors(django.setup)()
  File "J:\good\test\Lib\site-packages\django\utils\autoreload.py", line 64, in wrapper
    fn(*args,**kwargs)
  File "J:\good\test\Lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "J:\good\test\Lib\site-packages\django\apps\registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
                 ^^^^^^^^^^^^^^^^^^^^^^^
  File "J:\good\test\Lib\site-packages\django\apps\config.py", line 193, in create
    import_module(entry)
  File "C:\Program Files\Python311\Lib\importlib\__init__.py", line 128, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1206, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1178, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1137, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'threeapp.apps.threeappConfig'; 'threeapp.apps' is not a package

项目代码文件

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', 'one.settings.dev')
    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()

models.py

from django.db import models

# Create your models here.
class register(models.Model):
    name = models.CharField(max_length=30)
    Email= models.EmailField(max_length=254)
    phone= models.IntegerField(max_length=13)
    account = models.CharField(max_length=10)
    message = models.CharField(max_length=300)

settings/dev.py

import os
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.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-@5jng)a#7^9ud*b$1!vmmyjbei2-h758^w7vj72oli+eo+th@t'

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

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'threeapp.apps.threeappConfig',
    '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 = 'one.urls'

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


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'jeeva',
        'USER':'postgres',
        'PASSWORD':'9487',
        'HOST':'localhost'

        
    }
}


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

STATIC_URL = 'static/'
STATICFILES_DIRS=[
    os.path.join(BASE_DIR,'static')
]
STATIC_ROOT=os.path.join(BASE_DIR,'asserts')



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

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

项目结构

one/
├── one/
│   ├── __init__.py
│   ├── settings/
│   │   ├── __init__.py
│   │   └── dev.py
│   ├── urls.py
│   └── wsgi.py
├── threeapp/
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations/
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── manage.py
├── static/
└── templet/

修复步骤

1. 修正INSTALLED_APPS配置

错误根源是threeapp.apps.threeappConfig的类名大小写错误,Django要求AppConfig类名首字母大写,或直接使用应用名简化配置。修改one/settings/dev.py中的INSTALLED_APPS:

INSTALLED_APPS = [
    # 推荐:直接使用应用名,无需配置AppConfig路径
    'threeapp',
    # 若要使用AppConfig,需修正类名大小写
    # 'threeapp.apps.ThreeappConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

2. 确保apps.py文件有效性(若使用AppConfig路径)

如果坚持使用AppConfig路径,检查threeapp/apps.py是否存在,内容需符合规范:

from django.apps import AppConfig

class ThreeappConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'threeapp'

3. 安装PostgreSQL驱动

确保已安装适配Django的PostgreSQL驱动:

pip install psycopg2-binary

4. 修正模型字段错误

模型中phone字段使用IntegerField却设置max_length,该参数对IntegerField无效,建议改为CharField(电话号码通常含非数字前缀或符号):

# 修改models.py中的phone字段
phone = models.CharField(max_length=13)

5. 执行迁移命令

完成以上修改后,执行迁移:

python manage.py makemigrations
python manage.py migrate

额外检查项

  • 确认PostgreSQL服务已启动,数据库jeeva已提前创建
  • 验证数据库账号postgres的密码9487正确,且拥有jeeva数据库的操作权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 23:38:18