How to connect Django ORM to mongo atlas?

前端 未结 5 596
情深已故
情深已故 2020-12-21 10:41

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:

相关标签:
5条回答
  • 2020-12-21 11:06

    Simplest and correct solution:

    Step 1: Install djongo and dnspython

    pip install djongo

    pip install dnspython

    Step 2: Changes in settings.py:

    DATABASES = {
    "default": {
        "ENGINE": "djongo",
        "CLIENT": {
            "host": "mongodb+srv://<username>:<password>@<cluster_name>.mongodb.net/?retryWrites=true&w=majority",
            "username": "<username>",
            "password": "<password>",
            "name": "<database_name>",
            "authMechanism": "SCRAM-SHA-1",
        },
    }}
    
    0 讨论(0)
  • 2020-12-21 11:17

    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.

    0 讨论(0)
  • 2020-12-21 11:19

    Got this working without any hack as follows:

    1. Install pip install dnspython.
    2. Update settings.py with the following,
    'default': {
            'ENGINE': 'djongo',
            'NAME': '<dbname>',
            'CLIENT': {
                'host': "mongodb+srv://<username>:" + quote_plus('<password>') + "@<cluster-name>.mongodb.net/test?retryWrites=true&w=majority"
            },   
        }
    
    1. Run python manage.py makemigrations
    2. Run python manage.py migrate
    0 讨论(0)
  • 2020-12-21 11:21

    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!

    0 讨论(0)
  • 2020-12-21 11:23

    I have managed to connect to mongo atlas with djongo by using the snippet from @Market Ahead here

    It looks like they dont want the password to have weird characters inside. In such case, even escaping is not working optimally.

    0 讨论(0)
提交回复
热议问题