6
respostas

erro ao executar docker-compose run web python manage.py makemigrations

Toda vez que tento rodar o comando do makemigrations, a console exibe o código abaixo. Já olhei outros tópicos e fiz as alterações sugeridas, mas o problema persiste.

docker-compose.yml

db: image: mysql:5.7 ports:

  - '3306:3306'
environment:
   MYSQL_DATABASE: 'todo_dev'
   MYSQL_USER: 'devops_dev'
   MYSQL_PASSWORD: 'mestre'
   MYSQL_ROOT_PASSWORD: 'senha'

.env

DB_NAME = "todo_dev" DB_USER = "devops_dev" DB_PASSWORD = "mestre" DB_HOST = "db" DB_PORT = "3306"


WARNINGS:
core.Todo.created_at: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
Migrations for 'core':
  core/migrations/0006_auto_20200508_1450.py
    - Alter field created_at on todo
6 respostas

Olá Thiago, tudo bem? Bastante estranho esse erro, mas você poderia verificar a data e hora do container? A aplicação está reclamando quanto ao timezone, então você poderia verificar data e hora da sua máquina e do container. Talvez seja apenas isso.

Fico aguardando retorno!

Chequei as datas tanto no container web quanto do mysql e ambos estão com data correta em UTC.

❯ docker-compose run web python manage.py makemigrations
Starting devops-master_db_1 ... done
System check identified some issues:

WARNINGS:
core.Todo.created_at: (fields.W161) Fixed default value provided.
    HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection
    self.connect()
  File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 227, in get_new_connection
    return Database.connect(**conn_params)
  File "/usr/local/lib/python3.6/site-packages/MySQLdb/__init__.py", line 84, in Connect
    return Connection(*args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 164, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
MySQLdb._exceptions.OperationalError: (2003, 'Can\'t connect to MySQL server on \'db\' (111 "Connection refused")')

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

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 103, in handle
    loader.check_consistent_history(connection)
  File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 281, in check_consistent_history
    applied = recorder.applied_migrations()
  File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 61, in applied_migrations
    if self.has_table():
  File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 44, in has_table
    return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
  File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 255, in cursor
    return self._cursor()
  File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 232, in _cursor
    self.ensure_connection()
  File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection
    self.connect()
  File "/usr/local/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection
    self.connect()
  File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect
    self.connection = self.get_new_connection(conn_params)
  File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 227, in get_new_connection
    return Database.connect(**conn_params)
  File "/usr/local/lib/python3.6/site-packages/MySQLdb/__init__.py", line 84, in Connect
    return Connection(*args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 164, in __init__
    super(Connection, self).__init__(*args, **kwargs2)
django.db.utils.OperationalError: (2003, 'Can\'t connect to MySQL server on \'db\' (111 "Connection refused")')

Tentei acessar a aplicação web, ai informei um login e senha apenas para testar. Mas ai a aplicação quebrou e mostrou uma mensagem de conexão recusada do banco de dados.

OperationalError at /login/
(2003, 'Can\'t connect to MySQL server on \'db\' (111 "Connection refused")')
Request Method:    POST
Request URL:    http://localhost:8000/login/?next=/
Django Version:    2.1.7
Exception Type:    OperationalError
Exception Value:    
(2003, 'Can\'t connect to MySQL server on \'db\' (111 "Connection refused")')
Exception Location:    /usr/local/lib/python3.6/site-packages/MySQLdb/connections.py in __init__, line 164
Python Executable:    /usr/local/bin/python
Python Version:    3.6.8
Python Path:    
['/usr/src/app',
 '/usr/local/bin',
 '/usr/local/lib/python36.zip',
 '/usr/local/lib/python3.6',
 '/usr/local/lib/python3.6/lib-dynload',
 '/usr/local/lib/python3.6/site-packages']
Server time:    Tue, 12 May 2020 16:58:36 -0300

Tiago, já entendi o problema, a questão é que eu estava usando uma imagem criada por mim mesmo certo. No caso como você está usando a imagem fornecida pelo instrutor, você realmente precisa alterar o arquivo deixando da seguinte forma:

version: '3'


services:
  db:
    image: mysql:5.7
    ports:
      - '3306:3306'
    environment:
      MYSQL_DATABASE: 'todo_dev'
      MYSQL_USER: 'devops_dev'
      MYSQL_PASSWORD: 'mestre'
      MYSQL_ROOT_PASSWORD: 'senha'
    # volumes:
    #   - /home/jonilson/alura/11-Gitlab-CI-e-Docker/mysqld:/var/run/mysqld
  web:
    image: aluracursos/django_todolist_image_build
    volumes:
      - ./env:/usr/src/app/to_do/.env
    ports:
      - "8009:8000"
    depends_on:
      - db

E excluir os containers criados com o comando:

docker-compose down

E depois criar os container novamente com o comando:

docker-compose up --build

E por fim usar o comando:

docker-compose run web python manage.py makemigrations

E fala pra gente se funcionou!

Não funcionou... apenas diminui a stack trace do error. Eu baixei o projeto disponibilizado na aula 02, se não me engano... teria como verificar se esse projeto está tudo ok?!

O erro continua insistindo nessa questão do tipo default do campo data, como se tivesse que mudar o tipo dele para um do django. Eu tentei mudar no script 0001_initial.py o tipo do default para o sugerido, mas não adianto... parece que ele está executando o script sql de outro lugar, sei lá...

❯ docker-compose run web python manage.py makemigrations
Starting devops-master_db_1 ... done
System check identified some issues:

WARNINGS:
core.Todo.created_at: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
Migrations for 'core':
  core/migrations/0006_auto_20200514_1513.py
    - Alter field created_at on todo

Tiago, eu testei usando esse mesmo projeto com a imagem do professor e essa Warning:

WARNINGS:
core.Todo.created_at: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`

Porém como você pode ver abaixo ele informa:

Migrations for 'core':
  core/migrations/0006_auto_20200514_1513.py
    - Alter field created_at on todo

E isso significa que as migrations foram criadas com sucesso, e você já pode executar os outros comandos:

docker-compose run web python manage.py migrate
docker-compose run web python manage.py createsuperuser

E pronto! Ou se preferir você pode entrar dentro do container web com o comando:

docker exec -it devops_web_1 bash

E depois executar os comandos restantes da seguinte forma:

python manage.py migrate
python manage.py createsuperuser

Espero ter ajudado!