Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect Django ORM to mongo atlas?

I am trying to connect my django instance to a mongo db cluster using django. I have checked from various sources and the way it is getting closer to work is:

  • Install dnspython
  • Have the following DATABASES dict in settings.py
DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': 'test',
        'HOST': 'mongodb+srv://mongo_usr:' + urllib.parse.quote('mypassword') + '@domain_assigned.mongodb.net/test?ssl=true&ssl_cert_reqs=CERT_NONE&retryWrites=true',
        'ENFORCE_SCHEMA': False
    }
}

It truly finds the endpoint but I am getting a weird error:

pymongo.errors.ServerSelectionTimeoutError: connection closed,connection closed,connection closed

has anyone fixed this before?

like image 960
py_script Avatar asked Apr 05 '19 21:04

py_script


People also ask

Can we connect Django with MongoDB?

Django is a SQL to mongodb query transpiler. Using django we can use MongoDB as a backend database for our Django project. We don't even need to change the Django ORM. The best part is that we can setup Django with MongoDB by adding just one line of code.

How does Django save data in MongoDB?

First, we setup Django Project with a MongoDB Connector. Next, we create Rest Api app, add it with Django Rest Framework to the project. Next, we define data model and migrate it to the database. Then we write API Views and define Routes for handling all CRUD operations (including custom finder).

Can we use NoSQL database with Django?

NoSQL databases are not officially supported by Django itself. There are, however, a number of side projects and forks which allow NoSQL functionality in Django. You can take a look on the wiki page which discusses some projects.


2 Answers

I just setup Djongo and MongoDB Atlas with the following:

DATABASES = {
        'default': {
        'ENGINE': 'djongo',
        'NAME': '<db name>',
        'HOST': 'mongodb+srv://<db username>:<db password>@....mongodb.net/test?retryWrites=true',
        'USER': '<db username>',
        'PASSWORD': '<db password>',
    }
}

Hope that helps!

like image 166
Market Ahead Avatar answered Oct 10 '22 17:10

Market Ahead


Install djongo package using pip install djongo.

Make sure you import following module:

import urllib

Setup database settings.

DATABASES = {
    'default': {
        'ENGINE': 'djongo',
        'NAME': '<db_name>',
        'HOST': "mongodb+srv://<db_username>:" +
                urllib.parse.quote_plus("<db_password>") +
                "@........mongodb.net/test?retryWrites=true&ssl=true&ssl_cert_reqs=CERT_NONE&w=majority",
    }
}

Substitute db_username, db_name and db_password with your credentials.

Also edit the host name given by Mongo Atlas.

like image 37
RoboMex Avatar answered Oct 10 '22 18:10

RoboMex