Django + Mongo + Docker getting pymongo.errors.ServerSelectionTimeoutError - django

I've been struggling to get a simple app running using Django, Djongo, Mongo, and Docker Compose. My setup looks like this:
docker-compose.yml
services:
mongodb:
image: mongo:latest
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: mongoadmin
MONGO_INITDB_DATABASE: django_mongodb_docker
ports:
- 27017:27017
web:
build: ./src
restart: always
command: python src/manage.py runserver 0.0.0.0:8000
volumes:
- .:/code
ports:
- 8000:8000
links:
- mongodb
Dockerfile
FROM python:3
ENV PYTHONUNBUFFERED=1
RUN mkdir /code
COPY . /code/
WORKDIR /code
COPY requirements.txt /code/
RUN pip install -r requirements.txt
settings.py
DATABASES = {
'default': {
'ENGINE': 'djongo',
'HOST': 'mongodb',
'PORT': 27017,
'USER': 'root',
'PASSWORD': 'mongoadmin',
'AUTH_SOURCE': 'admin',
'AUTH_MECHANISM': 'SCRAM-SHA-1',
}
}
What is annoying is that I am able to use pymongo from my web container to connect to the container running mongo. That works as follows.
from pymongo import MongoClient
c = MongoClient(
'mongodb://mongodb:27017',
username='root',
password='mongoadmin',
authSource='admin',
authMechanism='SCRAM-SHA-1')
print(c.server_info())
The issue is that when I go to run migrations from within my web container I get the following error.
Traceback (most recent call last):
File "/code/src/manage.py", line 22, in <module>
main()
File "/code/src/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 330, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 371, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 85, in wrapped
res = handle_func(*args, **kwargs)
File "/usr/local/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 92, in handle
executor = MigrationExecutor(connection, self.migration_progress_callback)
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/executor.py", line 18, in __init__
self.loader = MigrationLoader(self.connection)
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 53, in __init__
self.build_graph()
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/loader.py", line 216, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations
if self.has_table():
File "/usr/local/lib/python3.9/site-packages/django/db/migrations/recorder.py", line 56, in has_table
tables = self.connection.introspection.table_names(cursor)
File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/introspection.py", line 48, in table_names
return get_names(cursor)
File "/usr/local/lib/python3.9/site-packages/django/db/backends/base/introspection.py", line 43, in get_names
return sorted(ti.name for ti in self.get_table_list(cursor)
File "/usr/local/lib/python3.9/site-packages/djongo/introspection.py", line 47, in get_table_list
for c in cursor.db_conn.list_collection_names()
File "/usr/local/lib/python3.9/site-packages/pymongo/database.py", line 863, in list_collection_names
for result in self.list_collections(session=session, **kwargs)]
File "/usr/local/lib/python3.9/site-packages/pymongo/database.py", line 825, in list_collections
return self.__client._retryable_read(
File "/usr/local/lib/python3.9/site-packages/pymongo/mongo_client.py", line 1460, in _retryable_read
server = self._select_server(
File "/usr/local/lib/python3.9/site-packages/pymongo/mongo_client.py", line 1278, in _select_server
server = topology.select_server(server_selector)
File "/usr/local/lib/python3.9/site-packages/pymongo/topology.py", line 241, in select_server
return random.choice(self.select_servers(selector,
File "/usr/local/lib/python3.9/site-packages/pymongo/topology.py", line 199, in select_servers
server_descriptions = self._select_servers_loop(
File "/usr/local/lib/python3.9/site-packages/pymongo/topology.py", line 215, in _select_servers_loop
raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 5f9ecaa5bbdc0433baa13966, topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]>
In addition, I've tried to create a Djongo model and save it to see if maybe the problem is specific to migrations (essentially just trying to make any connection to mongo using djongo).
models.py
from djongo import models
class Blog(models.Model):
name = models.CharField(max_length=100)
test.py
b = Blog(name='test')
b.save()
That returns the following error:
The above exception was the direct cause of the following exception:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.9/site-packages/djongo/cursor.py", line 51, in execute
web_1 | self.result = Query(
web_1 | File "/usr/local/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 783, in __init__
web_1 | self._query = self.parse()
web_1 | File "/usr/local/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 884, in parse
web_1 | raise exe from e
web_1 | djongo.exceptions.SQLDecodeError:
web_1 |
web_1 | Keyword: None
web_1 | Sub SQL: None
web_1 | FAILED SQL: INSERT INTO "game_blog" ("name") VALUES (%(0)s)
web_1 | Params: ['test']
web_1 | Version: 1.3.3
web_1 |
web_1 | The above exception was the direct cause of the following exception:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
web_1 | return self.cursor.execute(sql, params)
web_1 | File "/usr/local/lib/python3.9/site-packages/djongo/cursor.py", line 59, in execute
web_1 | raise db_exe from e
web_1 | djongo.database.DatabaseError
web_1 |
web_1 | The above exception was the direct cause of the following exception:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
web_1 | response = get_response(request)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/core/handlers/base.py", line 179, in _get_response
web_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/views/generic/base.py", line 70, in view
web_1 | return self.dispatch(request, *args, **kwargs)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/views/generic/base.py", line 98, in dispatch
web_1 | return handler(request, *args, **kwargs)
web_1 | File "/code/src/game/views.py", line 9, in get
web_1 | b.save(using='mongo')
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 753, in save
web_1 | self.save_base(using=using, force_insert=force_insert,
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 790, in save_base
web_1 | updated = self._save_table(
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 895, in _save_table
web_1 | results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/base.py", line 933, in _do_insert
web_1 | return manager._insert(
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
web_1 | return getattr(self.get_queryset(), name)(*args, **kwargs)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1254, in _insert
web_1 | return query.get_compiler(using=using).execute_sql(returning_fields)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1397, in execute_sql
web_1 | cursor.execute(sql, params)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute
web_1 | return super().execute(sql, params)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute
web_1 | return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers
web_1 | return executor(sql, params, many, context)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
web_1 | return self.cursor.execute(sql, params)
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/utils.py", line 90, in __exit__
web_1 | raise dj_exc_value.with_traceback(traceback) from exc_value
web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute
web_1 | return self.cursor.execute(sql, params)
web_1 | File "/usr/local/lib/python3.9/site-packages/djongo/cursor.py", line 59, in execute
web_1 | raise db_exe from e
web_1 | django.db.utils.DatabaseError
Any help on this would be greatly appreciated.
I have tried editing my mongodb.conf like this already.

According to this document, the settings.py should have a CLIENT section which contains:
A set of key-value pairs that will be passed directly to MongoClient as kwargs while creating a new client connection.
So try setting your settings.py to:
DATABASE = {
'default': {
'ENGINE': 'djongo',
'NAME': 'your-database-name',
'CLIENT': {
'host': 'mongodb://mongodb:27017',
'username': 'root',
'password': 'mongoadmin',
'authSource': 'admin',
'authMechanism': 'SCRAM-SHA-1',
}
}
}

Related

How to establish a One to One relation in django model in mongo db?

I am using mongo db with djongo in django. I have two models Employee and PresentEmployee.
Employee:
class Employee(models.Model):
employee_id = models.CharField(primary_key=True, max_length=10, null=False, blank=False)
employee_name = models.CharField(max_length=200, null=False, blank=False)
email = models.EmailField(max_length=500, null=True, blank=True)
def __str__(self):
return self.employee_name
PresentEmployee:
class PresentEmployee(models.Model):
employee_id = models.OneToOneField(Employee, on_delete=models.CASCADE)
present_id = models.IntegerField(null=False, blank=False)
id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
def __str__(self):
return str(self.employee_id)
when I try to add a new object to PresentEmployee, I am getting the error
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 808, in __iter__
web_1 | yield from iter(self._query)
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 167, in __iter__
web_1 | yield self._align_results(doc)
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 269, in _align_results
web_1 | if selected.table == self.left_table:
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 133, in table
web_1 | return alias2token[name].table
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 133, in table
web_1 | return alias2token[name].table
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 133, in table
web_1 | return alias2token[name].table
web_1 | [Previous line repeated 917 more times]
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 130, in table
web_1 | name = self.given_table
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/sql_tokens.py", line 141, in given_table
web_1 | name = self._token.get_real_name()
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/sql.py", line 361, in get_real_name
web_1 | return self._get_first_name(dot_idx)
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/sql.py", line 386, in _get_first_name
web_1 | return token.get_name()
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/sql.py", line 355, in get_name
web_1 | return self.get_alias() or self.get_real_name()
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/sql.py", line 344, in get_alias
web_1 | _, ws = self.token_next_by(t=T.Whitespace)
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/sql.py", line 244, in token_next_by
web_1 | return self._token_matching(funcs, idx, end)
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/sql.py", line 223, in _token_matching
web_1 | if func(token):
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/sql.py", line 242, in <lambda>
web_1 | funcs = lambda tk: imt(tk, i, m, t)
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/utils.py", line 100, in imt
web_1 | elif types and any(token.ttype in ttype for ttype in types):
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/utils.py", line 100, in <genexpr>
web_1 | elif types and any(token.ttype in ttype for ttype in types):
web_1 | File "/usr/local/lib/python3.10/site-packages/sqlparse/tokens.py", line 19, in __contains__
web_1 | return item is not None and (self is item or item[:len(self)] == self)
web_1 | RecursionError: maximum recursion depth exceeded in comparison
web_1 |
web_1 | The above exception was the direct cause of the following exception:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/cursor.py", line 76, in fetchone
web_1 | return self.result.next()
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 797, in __next__
web_1 | result = next(self._result_generator)
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/sql2mongo/query.py", line 830, in __iter__
web_1 | raise exe from e
web_1 | djongo.exceptions.SQLDecodeError:
web_1 |
web_1 | Keyword: FAILED SQL: SELECT %(0)s AS "a" FROM "employees_employee" WHERE "employees_employee"."employee_id" = %(1)s LIMIT 1
web_1 | Params: (1, 'EMP1')
web_1 | Version: 1.3.6
web_1 | Sub SQL: None
web_1 | FAILED SQL: None
web_1 | Params: None
web_1 | Version: None
web_1 |
web_1 | The above exception was the direct cause of the following exception:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 98, in inner
web_1 | return func(*args, **kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/cursor.py", line 81, in fetchone
web_1 | raise db_exe from e
web_1 | djongo.database.DatabaseError
web_1 |
web_1 | The above exception was the direct cause of the following exception:
web_1 |
web_1 | Traceback (most recent call last):
web_1 | File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
web_1 | response = get_response(request)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
web_1 | response = wrapped_callback(request, *callback_args, **callback_kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/contrib/admin/options.py", line 686, in wrapper
web_1 | return self.admin_site.admin_view(view)(*args, **kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/utils/decorators.py", line 133, in _wrapped_view
web_1 | response = view_func(request, *args, **kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/views/decorators/cache.py", line 62, in _wrapped_view_func
web_1 | response = view_func(request, *args, **kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 242, in inner
web_1 | return view(request, *args, **kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1890, in add_view
web_1 | return self.changeform_view(request, None, form_url, extra_context)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/utils/decorators.py", line 46, in _wrapper
web_1 | return bound_method(*args, **kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/utils/decorators.py", line 133, in _wrapped_view
web_1 | response = view_func(request, *args, **kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1750, in changeform_view
web_1 | return self._changeform_view(request, object_id, form_url, extra_context)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1796, in _changeform_view
web_1 | form_validated = form.is_valid()
web_1 | File "/usr/local/lib/python3.10/site-packages/django/forms/forms.py", line 205, in is_valid
web_1 | return self.is_bound and not self.errors
web_1 | File "/usr/local/lib/python3.10/site-packages/django/forms/forms.py", line 200, in errors
web_1 | self.full_clean()
web_1 | File "/usr/local/lib/python3.10/site-packages/django/forms/forms.py", line 439, in full_clean
web_1 | self._post_clean()
web_1 | File "/usr/local/lib/python3.10/site-packages/django/forms/models.py", line 492, in _post_clean
web_1 | self.instance.full_clean(exclude=exclude, validate_unique=False)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 1464, in full_clean
web_1 | self.clean_fields(exclude=exclude)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 1516, in clean_fields
web_1 | setattr(self, f.attname, f.clean(raw_value, self))
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/models/fields/__init__.py", line 755, in clean
web_1 | self.validate(value, model_instance)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/models/fields/related.py", line 1090, in validate
web_1 | if not qs.exists():
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 1225, in exists
web_1 | return self.query.has_results(using=self.db)
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/query.py", line 592, in has_results
web_1 | return compiler.has_results()
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1363, in has_results
web_1 | return bool(self.execute_sql(SINGLE))
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1406, in execute_sql
web_1 | val = cursor.fetchone()
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 97, in inner
web_1 | with self:
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
web_1 | raise dj_exc_value.with_traceback(traceback) from exc_value
web_1 | File "/usr/local/lib/python3.10/site-packages/django/db/utils.py", line 98, in inner
web_1 | return func(*args, **kwargs)
web_1 | File "/usr/local/lib/python3.10/site-packages/djongo/cursor.py", line 81, in fetchone
web_1 | raise db_exe from e
web_1 | django.db.utils.DatabaseError
How can I establish a One to One relation from Employee model to PresentEmployee model. Like a OneToOneField in sql db like postgresql.
note: never mind the web_1 |, it is because I am using docker.
If you are using djongo, you can create EmbeddedField class:
class EmbeddedField(MongoField):
def __init__(
self,
model_container: typing.Type[Model],
model_form_class: typing.Type[forms.ModelForm] = None,
model_form_kwargs: dict = None,
*args,
**kwargs
):
After that, with your example you can create something like this
class Employee(models.Model):
employee_id = models.ObjectIdField()
employee_name = models.CharField(max_length=200, null=False, blank=False)
email = models.EmailField(max_length=500, null=True, blank=True)
def __str__(self):
return self.employee_name
class PresentEmployee(models.Model):
present_id = models.ObjectIdField()
employee = models.EmbeddedField(model_container=Employee)
id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
def __str__(self):
return str(self.employee_id)

Connecting Django docker to remote database

I have a Django application running on docker connected to a database in another container on the same host. This seams to work fine, but when I try to change the connection to a database on another server, it fails to connect. Not only that, but when I try to connect to the Django application in the browser(like admin or api) I get no response, and see no activity in the output log. The application runs fine with the remote database if I run it outside the container, and the database is set to accept all IPs for the user I am trying to connect with.
Any Ideas as to why I am not getting a connection?
Dockerfile:
FROM python:3.8-alpine
ENV PATH="/scripts:${PATH}"
COPY ./requirements.txt /requirements.txt
RUN apk add --update --no-cache --virtual .tmp gcc libc-dev linux-headers
RUN apk add mariadb-dev python3-dev postgresql-dev
RUN pip install -r /requirements.txt
RUN apk del .tmp
RUN mkdir /app_django
COPY ./app_django /app_django
WORKDIR /app_django
COPY ./scripts /scripts
RUN chmod +x /scripts/*
RUN mkdir -p /vol/web/media
RUN mkdir -p /vol/web/static
RUN adduser -D user
RUN chown -R user:user /vol
RUN chmod -R 755 /vol/web
USER user
CMD ["entrypoint.sh"]
docker-compose.yml
version: '3.7'
services:
db:
build: mysql/
environment:
MYSQL_ROOT_PASSWORD: 'password'
MYSQL_DATABASE: database
volumes:
- ./mysql/data:/var/lib/mysql
- ./mysql/conf:/etc/mysql/conf.d
- ./mysql/entrypoint-initdb.d:/docker-entrypoint-initdb.d/
- ./mysql/backup_database:/var/local/mysql/backups
ports:
- 3306:3306
restart: always
pdb:
build:
context: .
ports:
- "8000:8000"
volumes:
- ./pdb_django:/pdb_django
command: sh -c "python manage.py runserver 0.0.0.0:8000"
environment:
- DEBUG=1
entrypoint.sh
#!/bin/sh
set -e
python manage.py collectstatic --noinput
uwsgi --socket :8000 --master --enable-threads --module app.wsgi
Django db settings (the commented parts is used when conection to db on host container):
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'database',
'HOST': '<remote IP>',
# 'HOST': 'db',
'USER': 'user',
'PASSWORD': 'password',
'PORT': '3308'
# 'PORT': '3306',
}
}
requirements.txt
Django==3.1.4
uWSGI>=2.0.18,<2.1
django-filter==2.4.0
djangorestframework==3.12.2
mysql-connector-python==8.0.22
mysqlclient==2.0.2
PyMySQL==0.10.1
sqlparse==0.4.1
Outputlog for application:
pdb_1 | Watching for file changes with StatReloader
pdb_1 | Exception in thread django-main-thread:
pdb_1 | Traceback (most recent call last):
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
pdb_1 | self.connect()
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
pdb_1 | return func(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect
pdb_1 | self.connection = self.get_new_connection(conn_params)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
pdb_1 | return func(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 234, in get_new_connection
pdb_1 | return Database.connect(**conn_params)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 130, in Connect
pdb_1 | return Connection(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 185, in __init__
pdb_1 | super().__init__(*args, **kwargs2)
pdb_1 | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on '<remote IP>' (115)")
pdb_1 |
pdb_1 | The above exception was the direct cause of the following exception:
pdb_1 |
pdb_1 | Traceback (most recent call last):
pdb_1 | File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner
pdb_1 | self.run()
pdb_1 | File "/usr/local/lib/python3.8/threading.py", line 870, in run
pdb_1 | self._target(*self._args, **self._kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper
pdb_1 | fn(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run
pdb_1 | self.check_migrations()
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 459, in check_migrations
pdb_1 | executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/migrations/executor.py", line 18, in __init__
pdb_1 | self.loader = MigrationLoader(self.connection)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 53, in __init__
pdb_1 | self.build_graph()
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/migrations/loader.py", line 216, in build_graph
pdb_1 | self.applied_migrations = recorder.applied_migrations()
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 77, in applied_migrations
pdb_1 | if self.has_table():
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/migrations/recorder.py", line 55, in has_table
pdb_1 | with self.connection.cursor() as cursor:
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
pdb_1 | return func(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 259, in cursor
pdb_1 | return self._cursor()
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 235, in _cursor
pdb_1 | self.ensure_connection()
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
pdb_1 | return func(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
pdb_1 | self.connect()
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/utils.py", line 90, in __exit__
pdb_1 | raise dj_exc_value.with_traceback(traceback) from exc_value
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection
pdb_1 | self.connect()
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
pdb_1 | return func(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect
pdb_1 | self.connection = self.get_new_connection(conn_params)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner
pdb_1 | return func(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 234, in get_new_connection
pdb_1 | return Database.connect(**conn_params)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/MySQLdb/__init__.py", line 130, in Connect
pdb_1 | return Connection(*args, **kwargs)
pdb_1 | File "/usr/local/lib/python3.8/site-packages/MySQLdb/connections.py", line 185, in __init__
pdb_1 | super().__init__(*args, **kwargs2)
pdb_1 | django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on '<remote IP>' (115)")
It would seem this was an issue with my VPN. When I tried to run the container on a server on the network it worked fine, and I was also able to get responses when I turned off my VPN (although I could obviously not access the database on the server)

Docker-compose does not work in docker-machine

I have a cookiecutter-django application with docker that works fine if I run it locally with docker compose -f local.yml up. Now I am trying to deploy it so first I created a docker-machine in my computer (using macOS Catalina) and activated it.
Now, inside the docker-machine, the docker-compose build works fine, but when I run it, the application crashes.
Any idea what can be happening? I have been trying to solve this for almost a week now...
This are my logs when I do docker-compose up in the docker-machine:
Creating network "innovacion_innsai_default" with the default driver
Creating innovacion_innsai_postgres_1 ... done
Creating innovacion_innsai_django_1 ... done
Creating innovacion_innsai_node_1 ... done
Attaching to innovacion_innsai_postgres_1, innovacion_innsai_django_1, innovacion_innsai_node_1
postgres_1 | 2020-03-16 08:41:12.472 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
postgres_1 | 2020-03-16 08:41:12.472 UTC [1] LOG: listening on IPv6 address "::", port 5432
postgres_1 | 2020-03-16 08:41:12.473 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
postgres_1 | 2020-03-16 08:41:12.494 UTC [21] LOG: database system was shut down at 2020-03-16 08:31:09 UTC
postgres_1 | 2020-03-16 08:41:12.511 UTC [1] LOG: database system is ready to accept connections
django_1 | PostgreSQL is available
django_1 | Traceback (most recent call last):
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
django_1 | return self.cursor.execute(sql, params)
django_1 | psycopg2.errors.UndefinedTable: relation "innovation_sector" does not exist
django_1 | LINE 1: ...n_sector"."id", "innovation_sector"."sector" FROM "innovatio...
django_1 | ^
django_1 |
django_1 |
django_1 | The above exception was the direct cause of the following exception:
django_1 |
django_1 | Traceback (most recent call last):
django_1 | File "manage.py", line 30, in <module>
django_1 | execute_from_command_line(sys.argv)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
django_1 | utility.execute()
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
django_1 | self.fetch_command(subcommand).run_from_argv(self.argv)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
django_1 | self.execute(*args, **cmd_options)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 361, in execute
django_1 | self.check()
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check
django_1 | include_deployment_checks=include_deployment_checks,
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 65, in _run_checks
django_1 | issues.extend(super()._run_checks(**kwargs))
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks
django_1 | return checks.run_checks(**kwargs)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks
django_1 | new_errors = check(app_configs=app_configs)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique
django_1 | all_namespaces = _load_all_namespaces(resolver)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces
django_1 | url_patterns = getattr(resolver, 'url_patterns', [])
django_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
django_1 | res = instance.__dict__[self.name] = self.func(instance)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 584, in url_patterns
django_1 | patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__
django_1 | res = instance.__dict__[self.name] = self.func(instance)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/urls/resolvers.py", line 577, in urlconf_module
django_1 | return import_module(self.urlconf_name)
django_1 | File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
django_1 | return _bootstrap._gcd_import(name[level:], package, level)
django_1 | File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
django_1 | File "<frozen importlib._bootstrap>", line 983, in _find_and_load
django_1 | File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
django_1 | File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
django_1 | File "<frozen importlib._bootstrap_external>", line 728, in exec_module
django_1 | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
django_1 | File "/app/config/urls.py", line 18, in <module>
django_1 | path("", include("innovacion_innsai.innovation.urls", namespace="innovation")),
django_1 | File "/usr/local/lib/python3.7/site-packages/django/urls/conf.py", line 34, in include
django_1 | urlconf_module = import_module(urlconf_module)
django_1 | File "/usr/local/lib/python3.7/importlib/__init__.py", line 127, in import_module
django_1 | return _bootstrap._gcd_import(name[level:], package, level)
django_1 | File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
django_1 | File "<frozen importlib._bootstrap>", line 983, in _find_and_load
django_1 | File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
django_1 | File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
django_1 | File "<frozen importlib._bootstrap_external>", line 728, in exec_module
django_1 | File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
django_1 | File "/app/innovacion_innsai/innovation/urls.py", line 2, in <module>
django_1 | from innovacion_innsai.innovation import views
django_1 | File "/app/innovacion_innsai/innovation/views.py", line 9, in <module>
django_1 | from .analytics import alimentacion_cases, agro_cases, turismo_cases, movilidad_cases
django_1 | File "/app/innovacion_innsai/innovation/analytics.py", line 17, in <module>
django_1 | for case in Case.objects.filter(sector__sector=sectors[0]):
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 308, in __getitem__
django_1 | qs._fetch_all()
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 1242, in _fetch_all
django_1 | self._result_cache = list(self._iterable_class(self))
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/query.py", line 55, in __iter__
django_1 | results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1133, in execute_sql
django_1 | cursor.execute(sql, params)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute
django_1 | return super().execute(sql, params)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute
django_1 | return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
django_1 | return executor(sql, params, many, context)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
django_1 | return self.cursor.execute(sql, params)
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__
django_1 | raise dj_exc_value.with_traceback(traceback) from exc_value
django_1 | File "/usr/local/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
django_1 | return self.cursor.execute(sql, params)
django_1 | django.db.utils.ProgrammingError: relation "innovation_sector" does not exist
django_1 | LINE 1: ...n_sector"."id", "innovation_sector"."sector" FROM "innovatio...
django_1 | ^
django_1 |
innovacion_innsai_django_1 exited with code 1
node_1 |
node_1 | > innovacion_innsai#1.1.0 dev /app
node_1 | > gulp
node_1 |
node_1 | [08:41:22] Using gulpfile /app/gulpfile.js
node_1 | [08:41:22] Starting 'default'...
node_1 | [08:41:22] Starting 'styles'...
node_1 | [08:41:22] Starting 'scripts'...
node_1 | [08:41:22] Starting 'imgCompression'...
node_1 | [08:41:22] gulp-imagemin: Minified 0 images
This is my local.yml:
version: '3'
volumes:
local_postgres_data: {}
local_postgres_data_backups: {}
services:
django:
build:
context: .
dockerfile: ./compose/local/django/Dockerfile
image: innovacion_innsai_local_django
depends_on:
- postgres
volumes:
- .:/app
env_file:
- ./.envs/.local/.django
- ./.envs/.local/.postgres
ports:
- "8000:8000"
command: /start
postgres:
build:
context: .
dockerfile: ./compose/production/postgres/Dockerfile
image: innovacion_innsai_production_postgres
volumes:
- local_postgres_data:/var/lib/postgresql/data
- local_postgres_data_backups:/backups
env_file:
- ./.envs/.local/.postgres
#Estas dos siguientes lineas las he aƱadido yo luego
ports:
- "5432:5432"
node:
build:
context: .
dockerfile: ./compose/local/node/Dockerfile
image: innovacion_innsai_local_node
depends_on:
- django
volumes:
- .:/app
# http://jdlm.info/articles/2016/03/06/lessons-building-node-app-docker.html
- /app/node_modules
command: npm run dev
ports:
- "3000:3000"
# Expose browsersync UI: https://www.browsersync.io/docs/options/#option-ui
- "3001:3001"
And this is my .postgres file inside the .envs/local folder:
# PostgreSQL
# ------------------------------------------------------------------------------
POSTGRES_HOST=postgres
POSTGRES_PORT=5432
POSTGRES_DB=innovacion_innsai
POSTGRES_USER=debug
POSTGRES_PASSWORD=debug
File "/app/innovacion_innsai/innovation/analytics.py", line 17, in <module>
django_1 | for case in Case.objects.filter(sector__sector=sectors[0]):
It means that when django is initializing (the moment it loads the modules) it's doing DB queries on database that has no migrations applied. You need to transform whatever your code is doing on line 17 to run it lazy.

Django oracle its not working [duplicate]

I just want to connect my local oracle db with my django project but my database credential is not working. Actually, I'm able to connect my oracle database via sql developer with that credential:
I just used that credential in django settings_py like that
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'INTERNAL',
'USER': 'system',
'PASSWORD': 'oracle',
'HOST':'localhost/xe',
'PORT':'1521'
}
}
and error is:
Traceback (most recent call last):
web_1 | File "manage.py", line 22, in <module>
web_1 | execute_from_command_line(sys.argv)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
web_1 | utility.execute()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
web_1 | self.fetch_command(subcommand).run_from_argv(self.argv)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
web_1 | self.execute(*args, **cmd_options)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
web_1 | output = self.handle(*args, **options)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 110, in handle
web_1 | loader.check_consistent_history(connection)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 282, in check_consistent_history
web_1 | applied = recorder.applied_migrations()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations
web_1 | self.ensure_schema()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema
web_1 | if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()):
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 254, in cursor
web_1 | return self._cursor()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 229, in _cursor
web_1 | self.ensure_connection()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection
web_1 | self.connect()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__
web_1 | six.reraise(dj_exc_type, dj_exc_value, traceback)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
web_1 | raise value.with_traceback(tb)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection
web_1 | self.connect()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect
web_1 | self.connection = self.get_new_connection(conn_params)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/oracle/base.py", line 212, in get_new_connection
web_1 | return Database.connect(self._connect_string(), **conn_params)
web_1 | django.db.utils.DatabaseError: ORA-12545: Connect failed because target host or object does not exist
here its my listener status
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC_FOR_XE)))
STATUS of the LISTENER
------------------------
Alias LISTENER
Version TNSLSNR for Linux: Version 11.2.0.2.0 - Production
Start Date 28-DEC-2017 15:51:21
Uptime 0 days 2 hr. 8 min. 36 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Default Service XE
Listener Parameter File /u01/app/oracle/product/11.2.0/xe/network/admin/listener.ora
Listener Log File /u01/app/oracle/diag/tnslsnr/e48c7c272f44/listener/alert/log.xml
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC_FOR_XE)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=e48c7c272f44)(PORT=1521)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=e48c7c272f44)(PORT=8080))(Presentation=HTTP)(Session=RAW))
Services Summary...
Service "PLSExtProc" has 1 instance(s).
Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service...
Service "XE" has 1 instance(s).
Instance "XE", status READY, has 1 handler(s) for this service...
Service "XEXDB" has 1 instance(s).
Instance "XE", status READY, has 1 handler(s) for this service...
here its my listener status
You should change HOST to localhost' or '127.0.0.1 and SID is NAME.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'xe',
'USER': 'system',
'PASSWORD': 'oracle',
'HOST':'127.0.0.1',
'PORT':'1521'
}
}
For future references, if Oracle is configured with Service name instead of SID, then the configuration would be:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': '127.0.0.1:1521/service.name',
'USER': 'system',
'PASSWORD': 'oracle',
}
}
Another thing to consider when working with Oracle in Django is that when you connect to Other Users (schema) database, you have to set db_table Meta option in Django models:
class OracleTable(models.Model):
... fields ...
class Meta:
db_table = '\"OTHERUSER\".\"ORACLETABLE\"'

Django oracle db settings

I just want to connect my local oracle db with my django project but my database credential is not working. Actually, I'm able to connect my oracle database via sql developer with that credential:
I just used that credential in django settings_py like that
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'INTERNAL',
'USER': 'system',
'PASSWORD': 'oracle',
'HOST':'localhost/xe',
'PORT':'1521'
}
}
and error is:
Traceback (most recent call last):
web_1 | File "manage.py", line 22, in <module>
web_1 | execute_from_command_line(sys.argv)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
web_1 | utility.execute()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
web_1 | self.fetch_command(subcommand).run_from_argv(self.argv)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
web_1 | self.execute(*args, **cmd_options)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
web_1 | output = self.handle(*args, **options)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 110, in handle
web_1 | loader.check_consistent_history(connection)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/loader.py", line 282, in check_consistent_history
web_1 | applied = recorder.applied_migrations()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations
web_1 | self.ensure_schema()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 52, in ensure_schema
web_1 | if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()):
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 254, in cursor
web_1 | return self._cursor()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 229, in _cursor
web_1 | self.ensure_connection()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection
web_1 | self.connect()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/utils.py", line 94, in __exit__
web_1 | six.reraise(dj_exc_type, dj_exc_value, traceback)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise
web_1 | raise value.with_traceback(tb)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 213, in ensure_connection
web_1 | self.connect()
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 189, in connect
web_1 | self.connection = self.get_new_connection(conn_params)
web_1 | File "/usr/local/lib/python3.6/site-packages/django/db/backends/oracle/base.py", line 212, in get_new_connection
web_1 | return Database.connect(self._connect_string(), **conn_params)
web_1 | django.db.utils.DatabaseError: ORA-12545: Connect failed because target host or object does not exist
here its my listener status
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC_FOR_XE)))
STATUS of the LISTENER
------------------------
Alias LISTENER
Version TNSLSNR for Linux: Version 11.2.0.2.0 - Production
Start Date 28-DEC-2017 15:51:21
Uptime 0 days 2 hr. 8 min. 36 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Default Service XE
Listener Parameter File /u01/app/oracle/product/11.2.0/xe/network/admin/listener.ora
Listener Log File /u01/app/oracle/diag/tnslsnr/e48c7c272f44/listener/alert/log.xml
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC_FOR_XE)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=e48c7c272f44)(PORT=1521)))
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=e48c7c272f44)(PORT=8080))(Presentation=HTTP)(Session=RAW))
Services Summary...
Service "PLSExtProc" has 1 instance(s).
Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service...
Service "XE" has 1 instance(s).
Instance "XE", status READY, has 1 handler(s) for this service...
Service "XEXDB" has 1 instance(s).
Instance "XE", status READY, has 1 handler(s) for this service...
here its my listener status
You should change HOST to localhost' or '127.0.0.1 and SID is NAME.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'xe',
'USER': 'system',
'PASSWORD': 'oracle',
'HOST':'127.0.0.1',
'PORT':'1521'
}
}
For future references, if Oracle is configured with Service name instead of SID, then the configuration would be:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.oracle',
'NAME': '127.0.0.1:1521/service.name',
'USER': 'system',
'PASSWORD': 'oracle',
}
}
Another thing to consider when working with Oracle in Django is that when you connect to Other Users (schema) database, you have to set db_table Meta option in Django models:
class OracleTable(models.Model):
... fields ...
class Meta:
db_table = '\"OTHERUSER\".\"ORACLETABLE\"'