Search code examples
pythondjangomongodbherokumongodb-atlas

Heroku Deployment With MongoDB Error: Connection Refused


pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused Hello their, I am having a little bit of trouble trying to deploy my Django site in python. I am getting this error(shown above) when trying to connect with my MongoDB atlas database. I read that I have to whitelist my IP, but when I did it did not work. Here is my views.py file:

class Initialize():
    def __init__(self, name):
        self.name = name
        myclient = pymongo.MongoClient('mongodb+srv://<MY Username>:<My Password>@cluster0-gicez.mongodb.net/test?retryWrites=true&w=majority')
        global mydb
        mydb = myclient[f"{self.name}"]
        global userData
        userData = mydb["userData"]
        global authData
        authData = mydb["auth_user"]
        global storesCollection
        storesCollection = mydb["stores"]
        global mycolPostalCodes
        mycolPostalCodes = mydb["postalCodes"]

When I was running my code before I tried deploying it, the code worked fine. Also, here is my settings.py file:

DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'cluster0',
        'HOST' : 'mongodb+srv://<my username>:<my password>@cluster0-gicez.mongodb.net/test?retryWrites=true&w=majority',
        'USER': '<my username>',
        'PASSWORD': '<my password>',
    }
}

Any help would be much appreciated. Thanks. Please message me for more information if needed.


Solution

  • So, all I had to do was change my settings file. The way that I was connecting to mongodb atlas was outdated. So here is how I connected:

    DATABASES = {
        'default': {
            'ENGINE': 'djongo',
            'CLIENT': {
                'host': 'mongodb+srv://{username}:{password}@cluster0-gicez.mongodb.net/test?retryWrites=true&w=majority',
                'username': {username},
                'password': {password},
                'authMechanism': 'SCRAM-SHA-1'
            }
        }
    }