Z_Rekhi
Z_Rekhi

Reputation: 87

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.

Upvotes: 1

Views: 814

Answers (2)

Z_Rekhi
Z_Rekhi

Reputation: 87

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'
        }
    }
}

Upvotes: 1

D. SM
D. SM

Reputation: 14480

You need to whitelist the IP of the client, in this case Heroku. Their IP addresses are described here. Whitelisting your home/laptop IP does not allow Heroku to connect to your cluster.

To find out the address of a particular machine you could run e.g. the following code on the machine in question:

python -c "import urllib; print(urllib.urlopen('https://wtfismyip.com/text').read())"

Upvotes: 1

Related Questions