当我尝试运行命令时
docker-compose exec web python3 manage.py startapp accounts
此命令输出以下完整的错误消息。
Traceback (most recent call last):
File "/code/manage.py", line 22, in <module>
main()
File "/code/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.10/site-packages/django/core/management/__init__.py", line 416, in execute
django.setup()
File "/usr/local/lib/python3.10/site-packages/django/__init__.py", line 24, in setup
apps.populate(settings.INSTALLED_APPS)
File "/usr/local/lib/python3.10/site-packages/django/apps/registry.py", line 116, in populate
app_config.import_models()
File "/usr/local/lib/python3.10/site-packages/django/apps/config.py", line 269, in import_models
self.models_module = import_module(models_module_name)
File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/usr/local/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module>
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
File "/usr/local/lib/python3.10/site-packages/django/contrib/auth/base_user.py", line 58, in <module>
class AbstractBaseUser(models.Model):
File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 143, in __new__
new_class.add_to_class("_meta", Options(meta, app_label))
File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 371, in add_to_class
value.contribute_to_class(cls, name)
File "/usr/local/lib/python3.10/site-packages/django/db/models/options.py", line 243, in contribute_to_class
self.db_table, connection.ops.max_name_length()
File "/usr/local/lib/python3.10/site-packages/django/utils/connection.py", line 15, in __getattr__
return getattr(self._connections[self._alias], item)
File "/usr/local/lib/python3.10/site-packages/django/utils/connection.py", line 62, in __getitem__
conn = self.create_connection(alias)
File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 193, in create_connection
backend = load_backend(db["ENGINE"])
File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 113, in load_backend
return import_module("%s.base" % backend_name)
File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "/usr/local/lib/python3.10/site-packages/django/db/backends/postgresql/base.py", line 29, in <module>
raise ImproperlyConfigured("Error loading psycopg2 or psycopg module")
django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 or psycopg module
在研究方面,我尝试检查 psycopg 文档。文档告诉我运行命令 pip install psycopg2-binary 但这不起作用。 Psycopg 文档: https://www.psycopg.org/psycopg3/docs/basic/install.html
接下来我检查了堆栈溢出文章。我发现这篇文章Postgres with Django - 配置不当。错误:配置不当:加载 psycopg2 模块时出错:没有名为“psycopg2”的模块,但安装 psycopg2[二进制] 的解决方案不起作用。我还在 django 论坛上进行了搜索,但找不到答案。
在故障排除方面,我尝试卸载 django 和 psycopg,然后删除我的环境文件夹。之后,我尝试重新创建我的环境文件夹并使用 pip 重新安装 django 和 psycopg。
点列表输出
Package Version
----------------- -------
asgiref 3.7.2
Django 5.0
pip 23.2.1
psycopg 3.1.16
psycopg-binary 3.1.16
psycopg2-binary 2.9.9
setuptools 65.5.0
sqlparse 0.4.4
typing_extensions 4.9.0
设置.py
"""
Django settings for django_project project.
Generated by 'django-admin startproject' using Django 4.0.10.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/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.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-msd&ec*3%f9uohlh40ut)n%08pr-12#ewx73s@y&a*x00!4plo"
# 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 = "django_project.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 = "django_project.wsgi.application"
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
# django_project/settings.py
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "postgres",
"USER": "postgres",
"PASSWORD": "postgres",
"HOST": "db",
"PORT": 5432,
}
}
# 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/"
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
docker-compose.yml
version: "3.9"
services:
web:
build: .
command: python /code/manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- 8000:8000
depends_on:
- db
db:
image: postgres:13
volumes:
- postgres_data:/var/lib/postgresql/data/
environment:
- "POSTGRES_HOST_AUTH_METHOD=trust"
volumes:
postgres_data:
Dockerfile
# Pull base image
FROM python:3.10.4-slim-bullseye
# Set environment variables
ENV PIP_DISABLE_PIP_VERSION_CHECK 1
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# Set work directory
WORKDIR /code
# Install dependencies
COPY ./requirements.txt .
RUN pip install -r requirements.txt
# Copy project
COPY . .
Github链接 https://github.com/strikeouts27/django_for_professionals_bookstore
# Pull base image
FROM python:3.10.4-slim-bullseye
# Set environment variables
ENV PIP_DISABLE_PIP_VERSION_CHECK 1
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# Install system dependencies for psycopg
RUN apt-get update \
&& apt-get -y install build-essential libpq-dev \
&& apt-get clean
# Set work directory
WORKDIR /code
# Install dependencies
COPY ./requirements.txt .
RUN pip install -r requirements.txt
# Copy project
COPY . .
为了更好地参考 psycopg 的纯 Python 安装,请查看 psycopg 文档。
asgiref==3.7.2
Django==5.0
psycopg==3.1.16
psycopg-c==3.1.16
sqlparse==0.4.4
typing_extensions==4.9.0
此外,我注意到您的项目结构有一些潜在的改进。我很乐意在您的 GitHub 存储库上打开拉取请求,以建议最佳实践和增强功能。如果您有兴趣,请告诉我!