问题
I try to connect to use a MongoDB database for the Django project.
So I follow a tutorial for changing the DATABASE from settings.py
# Original
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'testDB',
}
Changed to
# From tutorials
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'testDB',
'USERNAME': 'username',
'PASSWORD': 'password',
'HOST': 'myhostname.example',
'PORT': '27017',
}
}
Trying to run
python manage.py makemigrations
python manage.py migrate
All works, but no data in my database
Apparently django went for the localhost:27017 host and created a database there.
Uninstalling MongoDB, just caused makemigrations to fail
pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [WinError 10061] No connection could be made because the target machine actively refused it
I found a solution. https://stackoverflow.com/a/60244703/7637454
To fulfill the answer here this is how you're supposed to configure it now.
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'yourmongodb',
'CLIENT': {
'host': 'some-host.or.ip',
'port': 27017,
'username': 'youruser',
'password': 'yourdbpass',
'authSource': 'yourcollection', # usually admin
}
},
}
回答1:
The answer provided, does not work for me, instead I adopted following approach.
So, behind the scene, the Django uses PyMongo and PyMongo's default configuration are:
class MongoClient(common.BaseObject):
HOST = "localhost" # here HOST has the hardcoded value
PORT = 27017
which are in the following file:
venv/lib/python3.6/site-packages/pymongo/mongo_client.py
replace the harcoded value of HOST
to something like
HOST = 'mongodb+srv://<username>:<password>@cluster-name/<dbname>?retryWrites=true&w=majority'
Additionally, we can set the environment variable if we want
HOST = os.getenv('MONGO_DB_URL')
来源:https://stackoverflow.com/questions/60582939/django-fails-to-connect-to-remote-mongodb-server-using-djongo