Skip to content

DOCSP-43200: Get started with Django #132

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions snooty.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,14 @@ sharedinclude_root = "https://raw.githubusercontent.com/10gen/docs-shared/main/"
driver-short = "PyMongo"
driver-long = "PyMongo, the MongoDB synchronous Python driver,"
driver-async = "PyMongo Async"
django-odm = "Django MongoDB"

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/Django MongoDB/Django MongoDB Backend/?

language = "Python"
mdb-server = "MongoDB Server"
mongo-community = "MongoDB Community Edition"
mongo-enterprise = "MongoDB Enterprise Edition"
docs-branch = "master" # always set this to the docs branch (i.e. master, 1.7, 1.8, etc.)
version-number = "4.10"
django-version-number = "5.0"
patch-version-number = "{+version-number+}.1" # always set this to the driver branch (i.e. 1.7.0, 1.8.0, etc.)
version = "v{+version-number+}"
stable-api = "Stable API"
Expand Down
28 changes: 28 additions & 0 deletions source/django-get-started.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
.. _django-get-started:

===============================
Get Started with {+django-odm+}
===============================

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

.. facet::
:name: genre
:values: tutorial

.. meta::
:description: Learn how to create an app to connect to a MongoDB deployment by using Django MongoDB.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

s/Django MongoDB/Django MongoDB Backend/

:keywords: quick start, tutorial, basics

.. toctree::

Download & Install </django-get-started/django-install/>
Create a Deployment </django-get-started/django-create-deployment/>
Create a Connection String </django-get-started/django-connection-string/>
Configure a MongoDB Connection </django-get-started/django-connect-mongodb/>
Create an Application </django-get-started/django-create-app/>
Write Data to MongoDB </django-get-started/django-write-data/>
89 changes: 89 additions & 0 deletions source/django-get-started/django-connect-mongodb.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
.. _django-get-started-connect:

=================================
Configure your MongoDB Connection
=================================

.. facet::
:name: genre
:values: tutorial

.. meta::
:keywords: app, odm, code example

.. procedure::
:style: connected

.. step:: Create a Django project

From your shell, run the following command to create a
new Django project called ``quickstart`` based on a custom template:

.. code-block:: bash

django-admin startproject quickstart --template https://github.com/mongodb-labs/django-mongodb-project/archive/refs/heads/{+django-version-number+}.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 an ``ObjectId`` value as each model's primary key

After running this command, your ``quickstart`` project has
the following file structure:

.. code-block:: bash

quickstart/
manage.py
mongo_migrations/
__init__.py
contenttypes/
auth/
admin/
quickstart/
__init__.py
apps.py
settings.py
urls.py
asgi.py
wsgi.py

.. step:: Update your database settings

Open your ``settings.py`` file and navigate to the ``DATABASES`` setting.
Replace this setting with the following code:

.. code-block:: bash

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

python


DATABASES = {
"default": {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The indentation is incorrect throughout these documents (only 3 spaces).

"ENGINE": "django_mongodb",
"NAME": "db",
"USER": "<username>",
"PASSWORD": "<password>",
"HOST": "<connection string URI>",
},
}

Replace the ``<username>`` and ``<password>`` placeholders with your
Atlas database user's username and password. Then, replace the
``<connection string URI>`` placeholder with the connection string
that you copied from the :ref:`django-get-started-connection-string`
step of this guide.
Copy link

@R-shubham R-shubham Jan 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@norareidy The connection string that user copies will have username and password by default. If they are using this approach then "HOST" will expect connection string in this format: "mongodb+srv://cluster0.example.mongodb.net". @Jibola / @aclark4life can you confirm?

Copy link

@aclark4life aclark4life Jan 13, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are at least two things going on here:

  • DATABASES dictionary: DATABASES["default"]["HOST"] can accept a prefix of mongodb+srv:// but does not require one.
  • django_mongodb_backend.parse_uri: Connection string is terminology only used in the context of parse_uri and in that context, the MONGODB_URI from Atlas can be "cut and pasted" with the exception of the NAME key which is not present in the Atlas MONGODB_URI but must be present in the parse_uri connection string.

To put it another way:

  • DATABASES dictionary: DATABASES["default"]["NAME"] must be defined. -or-
  • django_mongodb_backend.parse_uri: MONGODB_URI must include /mydatabase e.g. mongodb+srv://cluster0.example.mongodb.net/mydatabase.

Again, if it's easier to steer clear of parse_uri for clarity's sake that's OK.


.. step:: Start the server

To verify that you installed {+django-odm+} and correctly configured
your project, run the following command from your project root:

.. code-block:: bash

python3 manage.py runserver

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe this is consistent with the rest of your documentation and you want to leave it alone, but if you are working in a Python 3 virtual environment, you can write python without the 3. Coming from Django's docs, it looks odd to include that 3 on all commands.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was going to raise this too, but would defer to MongoDB-wide conventions. If there are no such conventions, then I prefer python too.


Then, visit http://127.0.0.1:8000/. You should see a "Congratulations!"

Check failure on line 87 in source/django-get-started/django-connect-mongodb.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.Time24h2Digits] Show the hours, minutes, and seconds with two digits each, even if the leading digit is 0 ('1:8'). Raw Output: {"message": "[MongoDB.Time24h2Digits] Show the hours, minutes, and seconds with two digits each, even if the leading digit is 0 ('1:8').", "location": {"path": "source/django-get-started/django-connect-mongodb.txt", "range": {"start": {"line": 87, "column": 34}}}, "severity": "ERROR"}

Check failure on line 87 in source/django-get-started/django-connect-mongodb.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.AvoidSubjunctive] Avoid the subjunctive 'should'. Raw Output: {"message": "[MongoDB.AvoidSubjunctive] Avoid the subjunctive 'should'.", "location": {"path": "source/django-get-started/django-connect-mongodb.txt", "range": {"start": {"line": 87, "column": 47}}}, "severity": "ERROR"}
message and an image of a rocket.

61 changes: 61 additions & 0 deletions source/django-get-started/django-connection-string.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
.. _django-get-started-connection-string:

==========================
Create a Connection String
==========================

You can connect to your MongoDB deployment by providing a
**connection URI**, also called a *connection string*, which
instructs the driver on how to connect to a MongoDB deployment
and how to behave while connected.

The connection string includes the hostname or IP address and
port of your deployment, the authentication mechanism, user credentials
when applicable, and connection options.

To connect to an instance or deployment not hosted on Atlas, see
:ref:`pymongo-connection-targets` in the PyMongo documentation.

.. procedure::
:style: connected

.. step:: Find your MongoDB Atlas Connection String

To retrieve your connection string for the deployment that
you created in the :ref:`previous step <django-get-started-create-deployment>`,
log into your Atlas account and navigate to the
:guilabel:`Database` section and click the :guilabel:`Connect` button
for your new deployment.

.. figure:: /includes/figures/atlas_connection_select_cluster.png
:alt: The connect button in the clusters section of the Atlas UI

Proceed to the :guilabel:`Connect your application` section and select
"Python" from the :guilabel:`Driver` selection menu and the version
that best matches the version you installed from the :guilabel:`Version`
selection menu.

Select the :guilabel:`Password (SCRAM)` authentication mechanism.

Deselect the :guilabel:`Include full driver code example` option to view
the connection string.

.. step:: Copy your Connection String

Click the button on the right of the connection string to copy it to
your clipboard as shown in the following screenshot:

.. figure:: /includes/figures/atlas_connection_copy_string_python.png
:alt: The connection string copy button in the Atlas UI

.. step:: Update the Placeholders

Paste this connection string into a file in your preferred text editor
and replace the ``<username>`` and ``<password>`` placeholders with
your database user's username and password.

Save this file to a safe location for use in the next step.

After completing these steps, you have a connection string that
contains your database username and password.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You may want to delete the stray blank line(s) at the end of some documents. ;-)

128 changes: 128 additions & 0 deletions source/django-get-started/django-create-app.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
.. _django-get-started-create-app:

=====================
Create an Application
=====================

.. facet::
:name: genre
:values: tutorial

.. meta::
:keywords: app, odm, code example

.. procedure::
:style: connected

.. step:: Create a "sample_mflix" app

From your ``quickstart`` project directory, run the following command to create a
new Django app called ``sample_mflix`` based on a custom template:

.. code-block:: bash

python3 manage.py startapp sample_mflix --template https://github.com/mongodb-labs/django-mongodb-app/archive/refs/heads/5.0.x.zip

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use {+django-version-number+} as in startproject?


.. note:: App Template

The ``django-mongodb-app`` template ensures that your ``app.py`` file
includes the line ``"default_auto_field = 'django_mongodb.fields.ObjectIdAutoField'"``.

.. step:: Create a view

Open the ``views.py`` file in your ``sample_mflix`` directory and replace
its contents with the following code:

.. code-block:: python

from django.http import HttpResponse


def index(request):
return HttpResponse("Hello, world. You're at the application index.")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extra blank line compared to rest of example.

.. step:: Configure a URL

Create a new file called ``urls.py`` file in your ``sample_mflix`` directory and add
the following code:

.. code-block:: python

from django.urls import path

from . import views

urlpatterns = [
path("", views.index, name="index"),
]

Then, navigate to the ``quickstart/urls.py`` file and replace its contents with
the following code:

.. code-block:: python

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
path("sample_mflix/", include("sample_mflix.urls")),
path("admin/", admin.site.urls),
]

Visit http://127.0.0.1:8000/sample_mflix/ to see the text defined in your view.

Check failure on line 72 in source/django-get-started/django-create-app.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.Time24h2Digits] Show the hours, minutes, and seconds with two digits each, even if the leading digit is 0 ('1:8'). Raw Output: {"message": "[MongoDB.Time24h2Digits] Show the hours, minutes, and seconds with two digits each, even if the leading digit is 0 ('1:8').", "location": {"path": "source/django-get-started/django-create-app.txt", "range": {"start": {"line": 72, "column": 28}}}, "severity": "ERROR"}

.. step:: Apply database migrations

From your project root, run the following command:

.. code-block:: bash

python manage.py migrate

.. step:: Create models for movie and users data

Open the ``models.py`` file in the ``sample_mflix`` directory and replace
its contents with the following code:

.. code-block:: python

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

html+django


from django.db import models


class Movies(models.Model):
name = models.CharField(max_length=200)
runtime = models.IntegerField(default=0)


class Users(models.Model):
name = models.CharField(max_length=200)
email = models.CharField(max_length=200)


.. step:: Include your app in your project

Open the ``settings.py`` file in ``quickstart`` and edit your
``INSTALLED_APPS`` setting to resemble the following code:

.. code-block:: python

INSTALLED_APPS = [
'sample_mflix.apps.SampleMflixConfig',
'quickstart.apps.MongoAdminConfig',
'quickstart.apps.MongoAuthConfig',
'quickstart.apps.MongoContentTypesConfig',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]

.. step:: Create migrations for your new models

From your project root, run the following command to create
migrations for the ``Movies`` and ``Users`` models and Apply
the changes to the database:

.. code-block:: bash

python3 manage.py makemigrations sample_mflix

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sample_mflix is an existing database, so the models should have an inner Meta class with managed = False so that Django doesn't try to create the collections. Otherwise, I believe MongoDB will error with "collection already exists) at https://github.com/mongodb-labs/django-mongodb-backend/blob/eae01a45820de3b3a0efab4c1e85faa96335b4ad/django_mongodb_backend/schema.py#L25.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't cause an error for me, but happy to add!

python3 manage.py migrate

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sample_mflix is an existing database, so the models should have an inner Meta class with managed = False so that Django doesn't try to create (and otherwise modify) the collections. Otherwise, I believe MongoDB will error with "collection already exists) here when running migrate...

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@timgraham As well as set db_name correct?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, db_table is already set.

27 changes: 27 additions & 0 deletions source/django-get-started/django-create-deployment.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
.. _django-get-started-create-deployment:

===========================
Create a MongoDB Deployment
===========================

You can create a free tier MongoDB deployment on MongoDB Atlas
to store and manage your data. MongoDB Atlas hosts and manages
your MongoDB database in the cloud.

.. procedure::
:style: connected

.. step:: Create a Free MongoDB deployment on Atlas

Complete the :atlas:`Get Started with Atlas </getting-started?tck=docs_driver_python>`
guide to set up a new Atlas account and load sample data into a new free
tier MongoDB deployment.

.. step:: Save your Credentials

After you create your database user, save that user's
username and password to a safe location for use in an upcoming step.

After you complete these steps, you have a new free tier MongoDB
deployment on Atlas, database user credentials, and sample data loaded
in your database.
Loading
Loading