Skip to content

DOCSP-46328: Django connection configuration #142

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 all commits
Commits
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
1 change: 1 addition & 0 deletions snooty.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ 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 Backend"
language = "Python"
mdb-server = "MongoDB Server"
mongo-community = "MongoDB Community Edition"
Expand Down
179 changes: 179 additions & 0 deletions source/configure-connection.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
.. _django-connection-configuration:

==================================
Configure Your Database Connection
==================================

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: connection string, URI, server, settings

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

Overview
--------

In this guide, you can learn how to configure your Django project's
connection to MongoDB.

Connection Configuration
------------------------

After installing {+django-odm+} and creating a project, you can configure
your connection to MongoDB in the following ways:

- :ref:`django-connection-configure-manual` by specifying the
``DATABASES`` variable in your project's settings.
- :ref:`django-connection-configure-automatic` by using
the ``parse_uri()`` function.

.. tip::

To learn how to install {+django-odm+} and create a
Django project, visit the :ref:`django-get-started` tutorial.
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Note: this link is broken until #132 is merged


.. _django-connection-configure-manual:

Manually Configure Database Settings
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

To manually configure your connection to MongoDB, update
the ``DATABASES`` variable in your project's ``settings.py``
file. Set the ``DATABASES`` variable to a dictionary value containing
the ``default`` key, as shown in the following example:

.. code-block:: python

DATABASES = {
"default": {
# Specify nested dictionary keys here
},
}

To configure the ``default`` key, assign a nested dictionary as its value.
This nested dictionary has the following keys:

.. list-table::
:header-rows: 1
:widths: 20 80

* - Key
- Description

* - **ENGINE**
- The backend driver to use for the connection. Set this key to ``"django_mongodb_backend"``.

* - **HOST**
- | Your connection URI. For localhost connections, this key is optional.
| For SRV connections, you must include a scheme prefix (``mongodb+srv://``).
|
| To specify more than one host, include all hostnames in one string. Use
a comma to separate each hostname.
| **Example:** ``"HOST": "mongodb://mongos0.example.com:27017,mongos1.example.com:27017"``

* - **NAME**
- The database you want to use.

* - **USER**
- The username for authenticating to the database, if your connection
requires authentication.

* - **PASSWORD**
- The password for your database user, if your connection requires authentication.

* - **PORT**
Copy link

Choose a reason for hiding this comment

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

Here you can say the default port is 27017

- | The port number on which the database server is listening. The default
port is ``27017``.
| For MongoDB Atlas connections, this key is optional.

* - **OPTIONS**
- | A dictionary of additional connection options for the database. This key is optional.

Check failure on line 97 in source/configure-connection.txt

View workflow job for this annotation

GitHub Actions / TDBX Vale rules

[vale] reported by reviewdog 🐶 [MongoDB.ConciseTerms] 'more' is preferred over 'additional'. Raw Output: {"message": "[MongoDB.ConciseTerms] 'more' is preferred over 'additional'.", "location": {"path": "source/configure-connection.txt", "range": {"start": {"line": 97, "column": 26}}}, "severity": "ERROR"}
| To see a full list of connection options that you can set in the ``OPTIONS`` key,
see the optional parameters for `MongoClient <https://pymongo.readthedocs.io/en/4.10.1/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient>`__
in the PyMongo API documentation.

.. _django-manual-config-example:

Example
```````

In this example, the ``DATABASES`` variable performs the
following actions:

- Sets the database to ``my_database``
- Provides authentication information for a database user
whose username is ``my_user`` and password is ``my_password``
- Specifies the default MongoDB port (``27017``)
- Sets the ``retryWrites`` connection option to ``true``,
which configures the driver to automatically retry certain
write operations if they fail
- Sets the ``w`` connection option to ``majority``,
which configures the driver to wait for acknowledgement from a majority
of replica set members before performing write operations

.. code-block:: python

DATABASES = {
"default": {
"ENGINE": "django_mongodb_backend",
"HOST": "mongodb+srv://cluster0.example.mongodb.net",
"NAME": "my_database",
"USER": "my_user",
"PASSWORD": "my_password",
"PORT": 27017,
"OPTIONS": {
"retryWrites": "true",
"w": "majority",
},
},
}

.. _django-connection-configure-automatic:

Automatically Configure Database Settings
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

To automatically construct the ``DATABASES`` setting that configures
Copy link
Collaborator

Choose a reason for hiding this comment

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

q: does this literally construct the DATABASES variable in that file with that same structure? or does it just have the same effect on the client/connection?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

The Django MongoDB README says it "constructs a DATABASES setting equivalent to the first example" -- @Jibola is it accurate to say that parse_uri() automatically constructs this setting?

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.

parse_uri is a convenience method so if it helps to leave it out for clarity's sake then I would do that. That said, DATABASES has to exist and it has to have the required keys. For example, I can run Django without that setting but if I try to access the admin I get

settings.DATABASES is improperly configured. Please supply the ENGINE value. 
Check settings documentation for more details.

Also FWIW my preference for testing is currently: https://github.com/aclark4life/project-templates/blob/main/project_template/project_name/settings/__init__.py#L7 with MONGODB_URI set by direnv.

And finally, please note we currently use parse_uri in the project template.

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 seems accurate to say it's constructing the DATABASES setting, so I'll leave that in.
Since I'm showing how to configure the same settings as the previous example, I'll leave the MONGODB_URI variable that shows how to do that

your MongoDB connection, you can use the ``parse_uri()`` function. This
function accepts the following arguments:

- ``uri``: Your MongoDB connection URI.
- ``conn_max_age``: Configures persistent database connections.
This argument is optional. To learn more, see
`Persistent connections <https://docs.djangoproject.com/en/stable/ref/databases/#persistent-database-connections>`__
in the Django documentation.
- ``test``: Provides a dictionary of settings for test
databases. This argument is optional. To learn more, see
`the TEST setting <https://docs.djangoproject.com/en/stable/ref/settings/#test>`__
in the Django documentation.

Example
```````

The following example uses the ``parse_uri()`` function to specify
the same connection configuration as the previous :ref:`manual configuration <django-manual-config-example>`
example:

.. code-block:: python

import django_mongodb_backend

MONGODB_URI = "mongodb+srv://my_user:[email protected]/my_database?retryWrites=true&w=majority"
DATABASES["default"] = django_mongodb_backend.parse_uri(MONGODB_URI)

Additional Information
----------------------

To view a sample project that configures a MongoDB database connection,
see the :ref:`django-get-started-connect` step in the Getting Started
tutorial.

To learn more about Django settings, see `Settings <https://docs.djangoproject.com/en/stable/ref/settings/>`__
Copy link

Choose a reason for hiding this comment

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

NIT for future version mappings. We will need to have the links point to the correlating version. Right now it points to stable

in the Django documentation.
Loading