Configure your MongoDB Connection
After installing Django MongoDB Backend and creating a MongoDB Atlas deployment, you can create a Django project that connects to MongoDB.
Create a Django project
From your shell, run the following command to create a
new Django project called quickstart
based on a custom template:
django-admin startproject quickstart --template https://github.com/mongodb-labs/django-mongodb-project/archive/refs/heads/5.0.x.zip
Note
Project Template
The django-mongodb-project
template resembles the default Django project
template but makes the following changes:
Includes MongoDB-specific migrations
Modifies the
settings.py
file to instruct Django to use anObjectId
value as each model's primary key
After running this command, your quickstart
project has
the following file structure:
quickstart/ manage.py mongo_migrations/ __init__.py contenttypes/ auth/ admin/ quickstart/ __init__.py apps.py settings.py urls.py asgi.py wsgi.py
Update your database settings
Open your settings.py
file and navigate to the DATABASES
setting.
Replace this setting with the following code:
DATABASES = { "default": django_mongodb_backend.parse_uri("<connection string URI>"), }
Replace the <connection string URI>
placeholder with the connection string
that you copied from the Create a Connection String
step of this guide. This configures your Django app to connect to
your Atlas deployment and access the sample_mflix
sample database.
Start the server
To verify that you installed Django MongoDB Backend and correctly configured your project, run the following command from your project root:
python manage.py runserver
Then, visit http://127.0.0.1:8000/. This page displays a "Congratulations!" message and an image of a rocket.
After completing these steps, you have a Django project configured to use MongoDB.