简体   繁体   中英

Django cant connect to mongoDB atlas

Recently I started a project to make a Webserver using a Django backend with and a mongoDB database hosted on their Atlas platform so i don't have to worry about running it locally.

Im still in the early stages of setting it up and encountered the this error:

pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it

It might also be relevant to mention that i currently have no documents on the database or models in the form of Django apps, but I doubt that this is the probelm as when i run manage.py migrate i get the above error and not a "no app with label" error.

My database config in my settings.py currently looks like this:

DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'house-project',
        'HOST': 'mongodb+srv://<my-user-name>:<my-password>@house-project-9g5fo.gcp.mongodb.net/test?retryWrites=true&w=majority'
    }
}

I know that one of the common errors is having special characters in your password and username, i have made sure not to include any or escape them with hex characters. I have made sure to add my ip and user on the Atlas side. I have checked online for an exiting answer, to no avail. The closest question i found was: How to connect Django ORM to mongo atlas? , but this solution does not work for me sadly.

Any help would be great in trying to solve this problem, let me know if any additional info is needed about my setup let me know and i would be happy to provide it. I have also included a stacktrace in case it is relevant below.

Traceback (most recent call last):
  File "manage.py", line 20, in <module>
    main()
  File "manage.py", line 16, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\django\core\management\__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\django\core\management\base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\django\core\management\base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\django\core\management\commands\migrate.py", line 87, in handle
    executor = MigrationExecutor(connection, self.migration_progress_callback)
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__
    self.loader = MigrationLoader(self.connection)
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__
    self.build_graph()
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\django\db\migrations\loader.py", line 212, in build_graph
    self.applied_migrations = recorder.applied_migrations()
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\django\db\migrations\recorder.py", line 73, in applied_migrations
    if self.has_table():
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\django\db\migrations\recorder.py", line 56, in has_table
    return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor())
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\django\db\backends\base\introspection.py", line 48, in table_names
    return get_names(cursor)
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\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 "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\djongo\introspection.py", line 47, in get_table_list
    for c in cursor.db_conn.list_collection_names()
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\pymongo\database.py", line 856, in list_collection_names
    for result in self.list_collections(session=session, **kwargs)]
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\pymongo\database.py", line 818, in list_collections
    return self.__client._retryable_read(
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\pymongo\mongo_client.py", line 1453, in _retryable_read
    server = self._select_server(
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\pymongo\mongo_client.py", line 1253, in _select_server
    server = topology.select_server(server_selector)
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\pymongo\topology.py", line 233, in select_server
    return random.choice(self.select_servers(selector,
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\pymongo\topology.py", line 192, in select_servers
    server_descriptions = self._select_servers_loop(
  File "C:\Users\mkars\.virtualenvs\house-project-VuTUb3qx\lib\site-packages\pymongo\topology.py", line 208, in _select_servers_loop
    raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it```

The Djongo documentation is not correct or outdated. I was able to get my Django app to connect to a mongodb using the following settings:

DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'CLIENT': {
            'host': 'mongodb+srv://<URL>',
            'username': 'something',
            'password': 'somepass',
            'authMechanism': 'SCRAM-SHA-1'
        }
    }
}

I found a very hack-y solution. Jayadevan was correct, pymongo was trying to connect to my local host instead of the provided URI, despite me specifying host.

I was looking for why this might be, and i stumbled upon this github issue. There was a suegestion in this thread to change the host in mongo_client.py. This file can be found in your in the directory that your dependency files are in.

Changing the HOST in this file does allow my database to connect. This leads me to the belief that pymongo does not take into account the HOST that you specify.

If anyone knows either what I missed, or a way that I can either fix my current setup so that I dont have to use this workaround please let me know.

Same issue. This is indeed a very hacky way to modify the library settings in order to achieve the desired results. The problem could be stemming from two places: Either from the Djongo engine (most likely) which is not forwarding the specified HOST to pymongo's mongo_client.py constructor. The other source could be Django itself which is not calling the constructor the right way (unlikely). I want to deploy my project to Heroku but this is not possible since all the dependencies I install are going to have this bug and I can't change the HOST name manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM