Skip to content

Commit cf1ba4b

Browse files
committed
Added tutorial for integrating django with mongodb #21
1 parent 265dd91 commit cf1ba4b

File tree

1 file changed

+210
-16
lines changed

1 file changed

+210
-16
lines changed

docs/technologies/django/integrate-mongodb.mdx

Lines changed: 210 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,215 @@ import SubHeading from "@site/src/components/SubHeading";
99

1010
> Sample Project: https://github.com/app-generator/how-to-integrate-django-with-mongo
1111
12-
## Topics
13-
14-
- What is MongoDB
15-
- Why is different compared with relational DBMS like MySql, PostgreSQL
16-
- Instal MongoDB
17-
- [For Windows](https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-windows/)
18-
- [For Linux, Ubuntu](https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/)
19-
- Set up a basic Django project
20-
- Add dependencies for MongoDB
21-
- Update configuration & the project to use the connection
22-
- Create a superuser
23-
- Access the ADMIN Section
24-
- Visualize the data in MongoDB
25-
- Style the project using Soft Admin Theme
26-
- https://github.com/app-generator/django-admin-soft-dashboard
12+
## Introduction
13+
14+
### What is MongoDB
15+
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.
16+
17+
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.
18+
19+
### Why is different compared with relational DBMS like MySql, PostgreSQL
20+
- 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.
21+
22+
- Storage architecture: Relational databases use a fixed schema to enforce data consistency and use ACID transactions to ensure data integrity. MongoDB uses a flexible schema that allows for faster development and easier data evolution.
23+
24+
- 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.
25+
26+
- 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.
27+
28+
### Install MongoDB
29+
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.
30+
- [For Windows](https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-windows/#install-mongodb-community-edition)
31+
- [For Linux, Ubuntu](https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/)
32+
33+
Alternatively use [https://www.mongodb.com/try/download/community](https://www.mongodb.com/try/download/community), under `MongoDB Community Server Download`, using the dropdown menu select your platform and installation package. This provides a graphical user interface for the installation.
34+
35+
- On Windows, tick the box `Install MongoDB as a Service`, this ensures MongoB is started automatically.
36+
- On Linux, after installation is complete, run the command `sudo service mongod start` or `sudo systemctl start mongod
37+
` to start up the MongoDB server.
38+
39+
MongoDB shell (`Mongosh`) is used to interact with the MongoDB server from the terminal. For Linux, it is installed with the MongoDB server.
40+
For Windows `mongosh` is not installed with the MongoDB server, follow the link below to install `mongosh`
41+
- [Mongosh download](https://www.mongodb.com/try/download/shell)
42+
43+
* Under `MongoDB Shell Download` using the dropdown menu, select the preferred platform and installation package.
44+
* After the download is complete, double-click the file and follow the instructions to install the MongoDB shell
45+
46+
To use `mongosh` with Windows, you need to add it to PATH. follow the instructions [here](https://www.mongodb.com/docs/mongodb-shell/install/#add-the-mongosh-binary-to-your-path-environment-variable) to add `mongosh` to PATH.
47+
48+
Once installation is complete, run the command below to ensure `mongosh` was installed correctly.
49+
```bash
50+
$ mongosh
51+
...
52+
test> // mongosh cli
53+
test> exit() // exits mongosh
54+
```
55+
This shows that `mongosh` has successfully connected to the MongoDB server. Now you are ready to start development with MongoDB installed on your device.
56+
57+
## Setting up a basic Django project
58+
- 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
59+
```bash
60+
$ mkdir django-mongo-integration
61+
django-mongo-integration$ cd django-mongo-integration
62+
django-mongo-integration$ virtualenv venv
63+
```
64+
65+
- The command below activates the virtual environment
66+
On Linux/Mac:
67+
```bash
68+
django-mongo-integration$ source venv/bin/activate
69+
(ven) django-mongo-integration$
70+
```
71+
On Windows:
72+
```bash
73+
django-mongo-integration$ ./venv/Scripts/activate.bat
74+
(venv) django-mongo-integration$
75+
```
76+
77+
* 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.
78+
```bash
79+
(venv) django-mongo-integration$ pip install django
80+
(venv) django-mongo-integration$ django-admin startproject core .
81+
```
82+
The project is created in the current directory because of `.` added to the command.
83+
84+
## Add dependencies for MongoDB
85+
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`.
86+
87+
* Run the command below to install Djongo
88+
```bash
89+
(venv) django-mongo-integration$ pip install pymongo==3.12.3 djongo
90+
```
91+
92+
### Update project configuration to use MongoDB
93+
94+
* Open `core/settings.py` and make the following changes to allow Django uses `djongo` as the database engine.
95+
```py
96+
# core/settings.py
97+
...
98+
DATABASES = {
99+
'default': {
100+
'ENGINE': 'djongo',
101+
'NAME': 'your-db-name',
102+
}
103+
}
104+
...
105+
```
106+
107+
## Create a superuser
108+
Before creating a superuser, we need to apply the default database migration.
109+
* Run the command below to apply database migration and then create a superuser
110+
```bash
111+
(venv) django-mongo-integration$ python manage.py migrate
112+
(venv) django-mongo-integration$ python manage.py createsuperuser
113+
```
114+
After completing the prompt, you would have created a superuser. Now you can start the application and visit the admin panel using the superuser details entered earlier.
115+
116+
## Accessing the ADMIN Section
117+
* Run the application using the command below
118+
```
119+
(venv) django-mongo-integration$ python manage.py runserver
120+
```
121+
* 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.
122+
123+
![Django admin login](https://user-images.githubusercontent.com/57325382/233063737-2d0bd12b-aabe-49b7-8f41-6f3e62cb31c2.png)
124+
125+
![Django admin panel](https://user-images.githubusercontent.com/57325382/233064663-21561f00-6218-4acc-842d-464d7dfabd08.png)
126+
127+
![Django admin user page](https://user-images.githubusercontent.com/57325382/233064672-1c3ecb66-6322-49aa-b32b-d06f0aa96aad.png)
128+
129+
## Visualizing the data in MongoDB
130+
To see the data added to your database, open your terminal and run the following command
131+
* Start up the MongoDB shell using the command `mongosh`
132+
```bash
133+
$ mongosh <db_name> # replace db_name with the database name registered with the database engine
134+
db_name> // shows you MongoDB shell has started
135+
```
136+
* The command below will show you all the collections created when we made the database migration.
137+
```bash
138+
db_name> show tables
139+
__schema__
140+
auth_group
141+
auth_group_permissions
142+
auth_permission
143+
auth_user
144+
auth_user_groups
145+
auth_user_user_permissions
146+
django_admin_log
147+
django_content_type
148+
django_migrations
149+
django_session
150+
db_name>
151+
```
152+
* Run the command below to see all the users created
153+
```bash
154+
db_name> db.auth_user.find()
155+
[
156+
{
157+
_id: ObjectId("643f1d48e846350f2ed32428"),
158+
id: 1,
159+
password: 'pbkdf2_sha256$************************************',
160+
last_login: ISODate("2023-04-19T08:50:31.196Z"),
161+
is_superuser: true,
162+
username: 'admin',
163+
first_name: '',
164+
last_name: '',
165+
166+
is_staff: true,
167+
is_active: true,
168+
date_joined: ISODate("2023-04-18T22:44:23.958Z")
169+
}
170+
]
171+
db_name>
172+
```
173+
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.
174+
175+
## Style the project using Soft Admin Theme
176+
Now we have set up our Django project and also connected it to MongoDB using `djongo`. Now we will head on to adding a prebuilt theme to our Django project. The theme to be added is the [`Django admin soft dashboard`](https://github.com/app-generator/django-admin-soft-dashboard). The proceeding steps will guide you in integrating this theme with your Django project.
177+
178+
* Run the command below to install the theme
179+
```bash
180+
(venv) django-mongo-integration$ pip install django-admin-soft-dashboard
181+
```
182+
183+
* 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.
184+
```py
185+
# core/settings.py
186+
...
187+
INSTALLED_APPS = [
188+
'admin_soft.apps.AdminSoftDashboardConfig', # <-- New
189+
'django.contrib.admin',
190+
...
191+
]
192+
...
193+
LOGIN_REDIRECT_URL = '/'
194+
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
195+
...
196+
```
197+
* Next step is to add a route that points to the theme. Open `core/urls.py and make the following change
198+
```py
199+
# core/urls.py
200+
...
201+
from django.urls import path, include
202+
203+
urlpatterns = [
204+
path('admin/', admin.site.urls),
205+
path('', include('admin_soft.urls')), # <-- New
206+
]
207+
```
208+
209+
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`. Now we have a working Django project that is connected to MongoDB.
210+
211+
![Django login admin-soft](https://user-images.githubusercontent.com/57325382/233063947-54fb40ef-d53f-4a7c-837a-0307831ce500.png)
212+
213+
![Django admin panel](https://user-images.githubusercontent.com/57325382/233064656-959c91bc-7d54-4dd1-a65b-5431bc7f9100.png)
214+
215+
![Django admin user page](https://user-images.githubusercontent.com/57325382/233064668-610e98c4-c5f3-43e6-9ac5-17ac227ffa9c.png)
216+
27217
- Conclusions
28-
- Resources Section
218+
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](https://appseed.us/) for more templates like the one used for this tutorial.
219+
220+
## Resources
221+
* [Djongo Documentation](https://www.djongomapper.com/get-started/)
222+
* [Django Soft admin dashboard](https://github.com/app-generator/django-admin-soft-dashboard)
29223

0 commit comments

Comments
 (0)