Brad
Brad

Reputation: 11

docker-compose exec web python manage.py makemigrations problem

Problem

I created a new Django project and tried to change the database from default to PostgreSQL. After changing the DATABASES in settings.py, I tried to run python manage.py migrate in local environment and docker-compose containers. While it worked ok in local settings, the docker-compose didn't. It throws django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: No module named 'psycopg2'. error. So, is there any way to fix this?

Steps to replicate the error

OS: WSL Ubuntu 4.4.0-18362-Microsoft

  1. docker-compose up -d
  2. docker-compose exec web pipenv install psycopg2-binary==2.8.4
  3. docker-compose down
  4. docker-compose exec web python manage.py migrate

Database settings and Docker Files

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'postgres',
        'PASSWORD': 'Bardwolf@314',
        'HOST': 'localhost',
        'PORT': 5432
    }
}

My docker-compose.yml, Dockerfile

Dockerfile

FROM python:3.8

ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

WORKDIR /code

COPY Pipfile Pipfile.lock /code/

RUN pip install pipenv && pipenv install --system
RUN pipenv run pip install psycopg2-binary==2.8.4

COPY . /code/

docker-compose.yml

version: '3.7'

services:
    web:
        build: .
        command: python /code/manage.py runserver 0.0.0.0:8080
        volumes:
            - ./code
        
        ports:
            - 8080:8080
        depends_on:
            - db
        
    db:
        image: postgres:11

Upvotes: 1

Views: 2391

Answers (2)

Sonic Park
Sonic Park

Reputation: 19

You can use this way...

docker-compose exec web sh -c "python manage.py makemigrations --noinput"

Upvotes: 0

Linh Nguyen
Linh Nguyen

Reputation: 3890

Your Django running inside the web container so you need to go into that container to run django commands.

So when you run docker-compose down after exec install it will remove previous container

After you run docker-compose up

Just run the other 2 commands and don't run docker-compose down

if you want to run it manually

You can go into the container bash by:

docker-compose exec web /bin/bash

Once you are in the console then you can type:

python3 manage.py makemigrations

If you want to exit container bash shell just type exit

Upvotes: 1

Related Questions