This article is written by Anaiya Raisinghani (Developer Advocate @ MongoDB) and Nora Reidy (Technical Writer @ MongoDB)
Interested in diving into our Django MongoDB Backend integration? Follow along with this quickstart to create a Django application, connect that application to a MongoDB deployment, ensure your deployment is hosted on MongoDB Atlas, and interact with the data stored in your database using simple CRUD operations.
What is Django?
Let’s first go over what Django is. Django is a high speed model view controller framework for building web applications. There are a ton of key benefits of utilizing Django in projects, such as rapid development, a variety of services to choose from, great security, and impressive scalability. Django prides itself on being the best framework for producing flawless work efficiently. As we’ll see throughout this quickstart, it’s incredibly simple to get up and running with our Django MongoDB Backend integration.
Pre-requisites
To be successful with this quickstart, you’ll need a handful of resources:
- An IDE. This tutorial uses Visual Studio Code.
- Python 3.10 or later. We recommend using 3.12 in the environment.
- A MongoDB Atlas cluster.
Create your MongoDB cluster
Please follow the steps to create a MongoDB cluster on our free tier cluster which is free forever. Please make sure that the “Network Settings” are correctly set up for easy connection to the cluster, and that a secure username and password have been chosen. Once the cluster is configured, please make sure the connection string is in a safe place for later use.
Load in the sample data to the cluster, and in the connection string, specify a connection to the sample database we are using, sample_mflix
. Do this by adding the name of the database after the hostname, as shown in the code snippet below:
mongodb+srv://<username>:<password>@samplecluster.jkiff1s.mongodb.net/<database_name>?retryWrites=true&w=majority&appName=SampleCluster
Now that our cluster is ready, we can create our virtual environment!
Create your virtual environment
Our first step is to create our Python virtual environment. Virtual environments allow us to keep the necessary packages and libraries for a specific project in the correct environment without having to make changes globally that could impact other projects.
To do this, run:
python3.12 -m venv venv
Then, run:
source venv/bin/activate
Once the (venv)
is next to the directory name in the terminal, the virtual environment is correctly configured. Make sure that the Python version is correct (3.10 and above) by double checking with:
python —version
Once the virtual environment is set up, we can install our Django integration!
Installing Django MongoDB Backend
To install the Django integration, please run the following command from the terminal:
pip install django-mongodb-backend
If both PyMongo and Django are installed in the environment, please ensure that the PyMongo version is between 4.6 and 5.0, and that the Django version is between 5.0 and 5.1.
When correctly run, this is what we’ll see in our terminal:
Once this step is complete, our integration is correctly downloaded along with the dependencies that include Django and PyMongo required for success.
Create your Django project!
We’re all set up to create our Django project. This django-mongodb-project
template is about the same as the default Django project template, with a couple important changes. It includes MongoDB-specific migrations, and the settings.py
file has been modified to make sure Django uses an ObjectId value for each model’s primary key. It also includes MongoDB-specific app configurations for Django apps that have default_auto_field
set. This library allows us to create our own apps so we can set django_mongodb_backend.fields.ObjectIdAutoField
.
Run this command to create a new Django project called quickstart
:
django-admin startproject quickstart --template https://github.com/mongodb-labs/django-mongodb-project/archive/refs/heads/5.0.x.zip
Once this command is run, it will show up on the left-hand side of the project file:
Once you can see the quickstart
project, it’s time to update our database settings. To do this, go to the settings.py
file under the quickstart
folder and head over to the DATABASES
setting. Replace the ”<connection string URI>”
with the specific cluster URI including the name of the sample database:
DATABASES = {
"default": django_mongodb_backend.parse_uri("<connection string URI>"),
}
Now, we can make sure that we have correctly installed the Django MongoDB Backend and our project is properly set up. Make sure to be in the quickstart
folder and run this command:
python manage.py runserver
Click on the link or visit http://127.0.0.1:8000/. At this page, there will be a “Congratulations!” and a picture of a rocket:
Now that we know our setup has been successful, we can go ahead and create an actual application where we can interact with the sample data we previously downloaded! Let’s dive in.
Creating an application for our “sample_mflix” data
We are first going to create our sample_mflix
application. Head into the root directory of your project and run this command to create an application based on our custom template:
python manage.py startapp sample_mflix --template https://github.com/mongodb-labs/django-mongodb-app/archive/refs/heads/5.0.x.zip
The django-mongodb-app
template makes sure that your apps.py
file includes the line: “default_auto_field = ‘django_mongodb.fields.ObjectIdAutoField’”. This ensures that instead of using the original Django BigAutoField
for IDs, we are using MongoDB’s specific ObjectId feature.
Once you create your project, we are going to create models for our movie, viewer, and award data.
Create models for our movie, viewer, and award data
To create data models, all we have to do is open up our models.py
file inside of our newly created sample_mflix
directory and replace the entire file with the following code.
from django.db import models
from django.conf import settings
from django_mongodb_backend.fields import EmbeddedModelField, ArrayField
from django_mongodb_backend.models import EmbeddedModel
class Award(EmbeddedModel):
wins = models.IntegerField(default=0)
nominations = models.IntegerField(default=0)
text = models.CharField(max_length=100)
class Movie(models.Model):
title = models.CharField(max_length=200)
plot = models.TextField(blank=True)
runtime = models.IntegerField(default=0)
released = models.DateTimeField("release date", null=True, blank=True)
awards = EmbeddedModelField(Award, null=True, blank=True)
genres = ArrayField(models.CharField(max_length=100), null=True, blank=True)
class Meta:
db_table = "movies"
managed = False
def __str__(self):
return self.title
class Viewer(models.Model):
name = models.CharField(max_length=100)
email = models.CharField(max_length=200)
class Meta:
db_table = "users"
managed = False
def __str__(self):
return self.name
The Movie
model here represents our sample_mflix.movies
collection and stores information about various movies! The Viewer
model, on the other hand, represents the sample_mflix.users
collection and stores important user details for a movie streaming platform. The Award
model represents the embedded document values that are stored in the Movie
model.
Once this is done and the models.py
file is saved, let’s create views to display our data.
Create views to display our data
To display data from the sample_mflix
database, we’ll add views to the views.py
file. Open it up from your sample_mflix
directory and replace the contents with the code below.
Here, we are displaying a landing page message and information about the Movie
and Viewer
models we configured above:
from django.http import HttpResponse
from django.shortcuts import render
from .models import Movie, Viewer
def index(request):
return HttpResponse("Hello, world. You're at the application index.")
def recent_movies(request):
movies = Movie.objects.order_by("-released")[:5]
return render(request, "recent_movies.html", {"movies": movies})
def viewers_list(request):
viewers = Viewer.objects.order_by("name")[:10]
return render(request, "viewers_list.html", {"viewers": viewers})
Once we have finished this section, we are ready to move on and configure URLs for our views.
Configure URLs for our views
To be successful in this section, we need to create a new file called urls.py
inside of our sample_mflix
directory. This file maps the views we defined in the previous step to dedicated URLs.
Copy the code below into this new file:
from django.urls import path
from . import views
urlpatterns = [
path("recent_movies/", views.recent_movies, name="recent_movies"),
path("viewers_list/", views.viewers_list, name="viewers_list"),
path("", views.index, name="index")
]
Once that has been copied in, we can go ahead to our quickstart/urls.py
file and replace the file’s content with the code below:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("sample_mflix.urls")),
]
Once we’ve finished replacing the file’s content, we can create templates to properly format our data.
Create templates to format your data
First, create a templates
subdirectory inside of the sample_mflix
directory. Once this subdirectory is created, create a recent_movies.html
file inside of it. We are going to copy in the following code to format the movie data requested by the recent_movies
view:
<!-- templates/recent_movies.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Recent Movies</title>
</head>
<body>
<h1>Five Most Recent Movies</h1>
<ul>
{% for movie in movies %}
<li>
<strong>{{ movie.title }}</strong> (Released: {{ movie.released }})
</li>
{% empty %}
<li>No movies found.</li>
{% endfor %}
</ul>
</body>
</html>
Create another file in this same templates
subdirectory and call it viewers_list.html
. This template formats the user data that is requested by our viewers_list
view. Copy in the following code:
<!-- templates/viewers_list.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Viewers List</title>
</head>
<body>
<h1>Alphabetical Viewers List</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{% for viewer in viewers %}
<tr>
<td>{{ viewer.name }}</td>
<td>{{ viewer.email }}</td>
</tr>
{% empty %}
<tr>
<td colspan="2">No viewer found.</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
Now that your templates are in place, we can include our application inside of our project!
Including our application inside of our project
To do this, head over to the settings.py
file nested in the quickstart
directory and edit the INSTALLED_APPS
section to look like this:
INSTALLED_APPS = [
'sample_mflix.apps.SampleMflixConfig',
'quickstart.apps.MongoAdminConfig',
'quickstart.apps.MongoAuthConfig',
'quickstart.apps.MongoContentTypesConfig',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
Once that has been done, we can create migrations for our new models.
Create migrations for your new models
We want to create migrations for our Movie
, Award
, and Viewer
models and apply all these changes to the database. Head back to the root of your project and run the below commands:
python manage.py makemigrations sample_mflix
python manage.py migrate
Once the migrations are created, we have a basic Django MongoDB backend application! We can use this simple application to interact with our sample_mflix
database. This means running basic CRUD operations on the data.
So, let’s go over how to do that.
Write data
We are going to be working with a Python shell, so head back into the project’s root directory and bring up the shell with this command:
python manage.py shell
Once you’re in your shell, we can import the necessary classes and modules for creating a datetime
object. Do this by running the code below:
from sample_mflix.models import Movie, Award, Viewer
from django.utils import timezone
from datetime import datetime
Now, we’re ready to insert a movie into our database! We can do this by running the code below to create a Movie
object that stores data about a movie named “Minari”
, including its awards:
movie_awards = Award(wins=122, nominations=245, text="Won 1 Oscar")
movie = Movie.objects.create(
title="Minari",
plot="A Korean-American family moves to an Arkansas farm in search of their own American Dream",
runtime=217,
released=timezone.make_aware(datetime(2020, 1, 26)),
awards=movie_awards,
genres=["Drama", "Comedy"]
)
This Movie
object actually stores incorrect data about the movie: the runtime
value is listed as 217
, but the correct value is 117
.
Let’s fix this by running the code below:
movie.runtime = 117
movie.save()
Now, let’s insert a viewer into our database as well. We can do this by creating a Viewer
object that stores data about a viewer named “Abigail Carter”
. Run the following code to do so:
viewer = Viewer.objects.create(
name="Abigail Carter",
email="abigail.carter@fakegmail.com"
)
Let’s delete a Viewer
object. A movie viewer by the name of “Alliser Thorne” is no longer a member of the movie streaming service. To remove this viewer, run the code below:
old_viewer = Viewer.objects.filter(name="Alliser Thorne").first()
old_viewer.delete()
Once that’s done, exit your shell using this command:
exit()
Ensure we are in the quickstart
directory, and start the server using this command:
python manage.py runserver
Great! We can now go and make sure our Movies
model was correctly inserted into the database. Do this by accessing the link:
http://127.0.0.1:8000/recent_movies/
This is what you’ll see, with our latest movie right on top:
Let’s check our Viewer
model, as well. Visit the link: http://127.0.0.1:8000/viewers_list/.
There will be a list of 10 viewer names in our database. “Abigail Carter” will be at the top and the viewer “Alliser Thorne” will have been deleted:
Once these steps have been completed, documents in the sample_mflix
sample database will have been inserted and edited.
Now, we can query the data inside of our database.
Reading back our data
Open up your Python shell again, and please make sure that you have imported the necessary modules from when you first created the Python shell back under the step, “Write Data.”
from sample_mflix.models import Movie, Award, Viewer
from django.utils import timezone
from datetime import datetime
Once your shell is ready to go, we can query our users collection for a specific email.
We want to query our sample_mflix.users
collection for a user with the email ”jason_momoa@gameofthron.es”
. Do this by running the following:
from sample_mflix.models import Movie, Viewer
Viewer.objects.filter(email="jason_momoa@gameofthron.es").first()
This will return the name of our user:
<Viewer: Khal Drogo>
Now, let’s query our movies collection for runtime values.
In the same shell, run the following code to find movies that have a runtime
value that is less than 10
:
Movie.objects.filter(runtime__lt=10)
This will return a list of matching movies, as seen in the screenshot below:
Once this step is finished, feel free to run queries on any data stored inside the MongoDB cluster!
Let’s create an admin site
It’s possible to create a Django admin site so that users can edit their data straight from a web interface.
Let’s first create an admin user. From the root directory run the following code:
python manage.py createsuperuser
The terminal will ask for a username, email address, and password. Enter the following information below to create a user with specified credentials:
Username: admin
Email address: admin@example.com
Password: <admin-password>
Password (again): <admin-password>
To enter the admin site, run the following code:
python manage.py runserver
Access the site by visiting http://127.0.0.1:8000/admin/. A login screen will appear:
Enter the name and password that was created previously to log on.
Here, the following information is presented and users can edit their project authentication configuration through selection of the Groups
or Users
rows in the Authentication and Authorization
table.
Let’s edit the data in our users
sample collection. Remember that this is represented by the Viewer
model, which is not associated with the Users
row as shown in the admin panel.
Head to the sample_mflix/admin.py
file and paste in the code below:
from django.contrib import admin
from .models import Viewer
admin.site.register(Viewer)
Refresh the Django administration site and it will be updated:
Now, we are able to select a viewer object. Do this by clicking on the Viewers
row of the SAMPLE_MFLIX
table to see the list of viewers, as seen below:
At the top of the list, click on Abigail Carter
. From here, we will be able to see the Name
and Email
.
Here, we are able to edit the information, if chosen. Users are able to edit any field and hit the SAVE
button to save any changes.
Great job, you have just completed the Django MongoDB Backend Quickstart! In this quickstart, you:
- Created a Django application.
- Connected your Django application to a MongoDB deployment.
- Ensured your deployment is hosted on MongoDB Atlas.
- Interacted with the data that is stored inside of your cluster.
- Created a Django admin page.
To learn more about Django MongoDB Backend, please visit the docs and our repository on GitHub. If you have any questions, please feel free to connect with us in our MongoDB Developer Forum.
Top comments (0)