Skip to main content

Integrate Django with MongoDB

Learn how to integrate Django with MongoDB

This page explains how to integrate Django with MongoDB, two powerful and technologies used in many applications and production-ready projects.

The source code is saved on GitHub for later reference and support.

Django & MongoDB Integration


✅ Introduction

This section presents more insights regarding MongoDB and the power features compared to a Relational Database like MySql or PostgreSQL.

What is MongoDB

MongoDB is an open-source, document-oriented NoSQL database that was designed for scalability and high availability. MongoDB stores data in JSON-like documents, which makes it easy for developers to work with data because it does not require a fixed schema. This means you can store data without having to define a strict structure, which is different from traditional SQL databases.

MongoDB supports CRUD (Create, Read, Update, Delete) operations, ad-hoc queries, and indexing, making it an excellent choice for modern web and mobile applications. It is widely used across various industries because of its flexibility, scalability, and fast performance.

MongoDB vs Relational DBMS

Data Model

Relational databases use a tabular data model, where data is organized into tables with columns and rows. MongoDB uses a document-based data model, where data is stored as documents that can have varying structures and are typically organized in collections.

Storage Architecture

Relational Databases use a fixed schema to enforce data consistency and use ACID transactions to ensure data integrity. The acronym ACID refers to the four key properties of a transaction: atomicity, consistency, isolation, and durability MongoDB uses a flexible schema that allows for faster development and easier data evolution.

Query Language

Relational Databases use SQL (Structured Query Language) to query data, which is a declarative language that allows users to specify what data they want to retrieve. MongoDB uses a query language called the MongoDB Query Language (MQL), which is a JSON-based language that allows for complex queries of document-based data.

Use cases

Relational databases are well-suited for transactional systems, such as online banking or e-commerce applications, where data consistency and integrity are critical. MongoDB is better suited for use cases where data is less structured and more varied, such as social media or content management systems, where the flexibility of the document model allows for faster development and easier data evolution.


✅ Install MongoDB

For this tutorial, you need MongoDB installed on your device to get started. To install MongoDB follow the links below and follow the steps outlined to get it done.

Alternatively, use the Community Version Installer, under MongoDB Community Server Download, using the dropdown menu select your platform and installation package. This provides a graphical user interface for the installation.

  • On Windows, tick the box Install MongoDB as a Service, this ensures MongoB is started automatically.
  • On Linux, after installation is complete, run the following commands
$ sudo service mongod start
// OR
$ sudo systemctl start mongod

✅ MongoDB shell

Mongosh, the MongoDB shell is used to interact with the MongoDB server from the terminal. For Linux, it is installed with the MongoDB server. For Windows mongosh is not installed with the MongoDB server, and needs to be installed from this location:

  • Mongosh download
    • Under MongoDB Shell Download using the dropdown menu, select the preferred platform and installation package.
    • After the download is complete, double-click the file and follow the instructions to install the MongoDB shell

To use mongosh with Windows, you need to add it to PATH. follow the instructions here to add mongosh to PATH.

Once installation is complete, run the command below to ensure mongosh was installed correctly.

$ mongosh
...
test> // mongosh cli
test> exit() // exits mongosh

This shows that mongosh has successfully connected to the MongoDB server. Now you are ready to start development with MongoDB installed on your device.


✅ Create a Django Project

From the terminal run the following commands to create a new folder, change the directory into the new folder and create a new virtual environment

$ mkdir django-mongo-integration
$ cd django-mongo-integration
$ virtualenv venv

The command below activates the virtual environment

For Linux/Mac:

$ source env/bin/activate
(venv) $ # ready for commands

For Windows:

$ env\Scripts\activate
(venv) $ # ready for commands

Now that the virtual environment is activated, we can start installing the packages needed. Execute the following commands on your terminal to install Django and create a new Django project.

(venv) $ pip install django
(venv) $ django-admin startproject core .

The project is created in the current directory because of . added to the command.


Add dependencies for MongoDB

Django was built to integrate seamlessly with Relational Databases. To use MongoDB with Django and still leverage features like the database modeling, admin panel and so on, we will be needing a package called Djongo. The proceeding steps will help us install and configure our Django project to use Djongo.

  • Run the command below to install Djongo
(venv) $ pip install pymongo 
(venv) $ pip install djongo

Update Configuration for MongoDB

Open core/settings.py and make the following changes to allow Django uses djongo as the database engine.

# core/settings.py
...
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'your-db-name',
}
}
...

Create a Superuser

Before creating a superuser, we need to apply the default database migration. Run the command below to apply database migration and then create a superuser

(venv) $ python manage.py makemigrations
(venv) $ python manage.py migrate
(venv) $ python manage.py createsuperuser

At this point, the our MongoDB database should be provisioned with the new tables, and also you would have created a superuser. Now you can start the application and visit the admin panel using the superuser details entered earlier.


✅ Checking the information

just to double check the set up, we can access the admin section (reserved for superusers) or use the Django CLI to inspect the information.

Accessing the ADMIN Section

Run the application using the command below

(venv) $ python manage.py runserver

When the Django server starts running, open your browser and visit http://127.0.0.1:8000/admin. This is the route to the admin section. Once you log in you will see the admin panel, which lets you perform several actions, including adding users, deleting users, and assigning and removing roles.

Django admin login


Django admin panel


Django admin user page


Visualizing the data in MongoDB

To see the data added to your database, open your terminal and run the following command

Start up the MongoDB Shell using the command mongosh

$ mongosh <db_name> # replace db_name with the database name registered with the database engine
db_name> // shows you MongoDB shell has started

The command below will show you all the collections created when we made the database migration.

db_name> show tables
__schema__
auth_group
auth_group_permissions
auth_permission
auth_user
auth_user_groups
auth_user_user_permissions
django_admin_log
django_content_type
django_migrations
django_session
db_name>

List all the users created

db_name> db.auth_user.find()
[
{
_id: ObjectId("643f1d48e846350f2ed32428"),
id: 1,
password: 'pbkdf2_sha256$************************************',
last_login: ISODate("2023-04-19T08:50:31.196Z"),
is_superuser: true,
username: 'admin',
first_name: '',
last_name: '',
email: 'admin@admin.com',
is_staff: true,
is_active: true,
date_joined: ISODate("2023-04-18T22:44:23.958Z")
}
]
db_name>

This command will return a list of all the users registered. For now, we have only created the superuser, hence we have only one record in the database.


✅ Styling the Project

This section explains how to style the project with a an open-source theme that covers the admin section but also the rest of the website.

The theme to be added is the Django Soft Dashboard, a modern Bootstrap 5 Design from Creative-Tim, migrated to Django.

The proceeding steps will guide you in integrating this theme with your Django project.

Install the theme

(venv) $ pip install django-admin-soft-dashboard

Update Settings

After installation, we need to make changes to our project files to allow the project to recognize and use the theme. Open the file core/settings.py and make the following changes.

# core/settings.py
# ... (truncated content)

INSTALLED_APPS = [
'admin_soft.apps.AdminSoftDashboardConfig', # <-- New
'django.contrib.admin',
...
]

# ... (truncated content)

LOGIN_REDIRECT_URL = '/'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

# ... (truncated content)

Edit Routes

Next step is to add a route that points to the theme. Open `core/urls.py and make the following change

# core/urls.py
# ... (truncated content)

from django.urls import path, include # make sure you have the INCLUDE directive

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('admin_soft.urls')), # <-- New
]

Now that all these changes have been made, open your browser and head to http://127.0.0.1:8000/ to see the changes made. You can also check the admin dashboard by visiting http://127.0.0.1:8000/admin.

At this point, our Django & MongoDB project is also styled with a nice, modern design.

Django login admin-soft


Django admin panel


Django admin user page


✅ Conclusions

Congratulations on completing the tutorial, so far we have covered the basics of setting up a Django project, connecting Django with MongoDB, viewing data stored in our MongoDB database and also using a prebuilt theme to get a head start in developing a Django application.

To sum up, connecting Django to MongoDB is a relatively straightforward process that involves only a few steps. With the power of Django's web framework and MongoDB's scalability and high availability, your applications will be able to handle large volumes of data with ease.

By following the above steps, you'll be able to connect Django to MongoDB quickly and begin building powerful and scalable web applications. You can visit Appseed for more templates like the one used for this tutorial.

✅ Resources