Невозможно запустить миграции для веб-сервиса django с бэкендом postgresql через docker

Я пытаюсь развиваться в проекте книжного магазина, упомянутого в книге под названием

Django для профессионалов от Винсента

По мере того, как я пытаюсь расти на нем, мой requirements.txt вырос до

asgiref==3.5.2
Django==4.0.4
psycopg2-binary==2.9.3
sqlparse==0.4.2
django-crispy-forms==1.14.0
crispy-bootstrap5==0.6
django-allauth==0.50.0

с моим Dockerfile как

FROM python:3.8-slim-bullseye

# set environment variables
ENV PIP_DISABLE_PIP_VERSION_CHECK 1
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# # Set working directory
WORKDIR /code

# # Installing python dependencies
COPY ./requirements.txt .
RUN pip install -r requirements.txt

и мой docker-compose.yml как

# Mentioning which format of dockerfile
version: "3.9"
# services or nicknamed the container
services:
  # web service for the web
  web:
    # you should use the --build flag for every node package added
    build: .
    # Add additional commands for webpack to 'watch for changes and bundle it to production'
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - type: bind
        source: .
        target: /code
    ports:
      - "8000:8000"
    depends_on:
      - db
    environment:
      - "DJANGO_SECRET_KEY=django-insecure-m#x2vcrd_2un!9b4la%^)ou&hcib&nc9fvqn0s23z%i1e5))6&"
      - "DJANGO_DEBUG=True"
  # postgreSQL database server being constructed alongside
  db:
    image: postgres:13
    #
    volumes:
      - postgres_data:/var/lib/postgresql/data/
    # unsure of what this environment means.
    environment:
      - "POSTGRES_HOST_AUTH_METHOD=trust"
# Volumes set up
volumes:
  postgres_data:

Я не смог запустить миграции или создать суперпользователя. Основная причина, которую я вижу, заключается в том, что relation doesn't exist.

Пытаясь отладить его, ниже приведен список таблиц в моей базе данных postgres.

root@a8988e22cd23:/# psql -U postgres
psql (13.8 (Debian 13.8-1.pgdg110+1))
Type "help" for help.

postgres=# \dt
               List of relations
 Schema |       Name        | Type  |  Owner   
--------+-------------------+-------+----------
 public | django_migrations | table | postgres
(1 row)

Ошибка, которую я вижу, возникает при выполнении команды python

P:\StockWhiz> docker compose exec web python manage.py migrate        
Operations to perform:
  Apply all migrations: account, admin, auth, contenttypes, sessions, sites, socialaccount     
Running migrations:
  Applying account.0001_initial...Traceback (most recent call last):
  File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedTable: relation "accounts_customuser" does not exist


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 414, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 460, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 98, in wrapped
    res = handle_func(*args, **kwargs)
  File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 290, in handle
    post_migrate_state = executor.migrate(
  File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python3.8/site-packages/django/db/utils.py", line 91, in __exit__           raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/usr/local/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "accounts_customuser" does not exist

ошибка в консоли композиции:

stockwhiz-db-1   | 2022-11-04 13:36:40.562 UTC [36] ERROR:  relation "accounts_customuser" does not exist
", "accounts_customuser"."password", "accounts_customuser"."last_login", "accounts_customuser"."is_superuser", "accounts_customuser"."username", "accounts_customuser"."first_name", "accounts_customuser"."last_name", "accounts_customuser"."email", "accounts_customuser"."is_staff", "accounts_customuser"."is_active", "accounts_customuser"."date_joined" FROM "accounts_customuser" WHERE "accounts_customuser"."username" = 'admin' LIMIT 21
stockwhiz-db-1   | 2022-11-04 13:38:26.019 UTC [41] ERROR:  relation "accounts_customuser" does not existstockwhiz-db-1   | 2022-11-04 13:38:26.019 UTC [41] STATEMENT:  ALTER TABLE "account_emailaddress" ADD CONSTRAINT "account_emailaddress_user_id_2c513194_fk_accounts_customuser_id" FOREIGN KEY ("user_id") REFERENCES "accounts_customuser" ("id") DEFERRABLE INITIALLY DEFERRED

Не могли бы вы направить меня к решению проблемы.

Выполняли ли вы makemigrations перед запуском migrate? Если да, получаете ли вы при этом какую-либо ошибку?

Поэтому важен порядок, в котором встречаются migrations, и поскольку моя ошибка касалась таблицы accounts_customuser, я должен был выполнить

python manage.py makemigrations accounts

в котором было приложение, включающее модель accounts_customuser.

Общее makemigrations перед migrate может не сработать.

Вернуться на верх