diff --git a/snooty.toml b/snooty.toml index 083d8d1..b2a0dd1 100644 --- a/snooty.toml +++ b/snooty.toml @@ -7,7 +7,8 @@ intersphinx = [ "https://www.mongodb.com/docs/manual/objects.inv", ] toc_landing_pages = [ - "/interact-data" + "/get-started", + "/interact-data", ] [constants] @@ -16,4 +17,6 @@ api = "https://django-mongodb.readthedocs.io/en/latest/" mdb-server = "MongoDB Server" django-version = "5.0" django-docs = "https://docs.djangoproject.com/en/{+django-version+}" +django-api = "https://django-mongodb-backend.readthedocs.io/en/latest/" +pymongo-version = "4.10" pymongo-docs = "https://www.mongodb.com/docs/languages/python/pymongo-driver/current" diff --git a/source/get-started.txt b/source/get-started.txt new file mode 100644 index 0000000..142cddf --- /dev/null +++ b/source/get-started.txt @@ -0,0 +1,44 @@ +.. _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 Backend. + :keywords: quick start, tutorial, basics + +.. toctree:: + + Download & Install + Create a Deployment + Create a Connection String + Configure a MongoDB Connection + Create an Application + Write Data to MongoDB + Query MongoDB Data + Create an Admin Site + Next Steps + +{+django-odm+} is a Django database backend that uses PyMongo to connect +to MongoDB. This tutorial shows you how to create a Django app, connect to +a MongoDB cluster hosted on MongoDB Atlas, and interact with data in your cluster. + +.. tip:: + + MongoDB Atlas is a fully managed cloud database service that hosts your MongoDB + deployments. You can create your own free (no credit card required) MongoDB Atlas + deployment by following the steps in this guide. + +Follow this tutorial to connect a sample Django application to a MongoDB Atlas +deployment. \ No newline at end of file diff --git a/source/get-started/connect-mongodb.txt b/source/get-started/connect-mongodb.txt new file mode 100644 index 0000000..29d73e5 --- /dev/null +++ b/source/get-started/connect-mongodb.txt @@ -0,0 +1,88 @@ +.. _django-get-started-connect: + +================================= +Configure your MongoDB Connection +================================= + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :keywords: app, odm, code example + +After installing {+django-odm+} and creating a MongoDB Atlas deployment, +you can create a Django project that connects to MongoDB. + +.. 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+}.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 + :copyable: false + + 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:: python + + DATABASES = { + "default": django_mongodb_backend.parse_uri(""), + } + + Replace the ```` placeholder with the connection string + that you copied from the :ref:`django-get-started-connection-string` + step of this guide. This configures your Django app to connect to + your Atlas deployment and access the ``sample_mflix`` sample database. + + .. 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 + + python manage.py runserver + + Then, visit http://127.0.0.1:8000/. This page displays a "Congratulations!" + message and an image of a rocket. + +After completing these steps, you have a Django project configured +to use MongoDB. \ No newline at end of file diff --git a/source/get-started/connection-string.txt b/source/get-started/connection-string.txt new file mode 100644 index 0000000..905d7d0 --- /dev/null +++ b/source/get-started/connection-string.txt @@ -0,0 +1,74 @@ +.. _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 `, + log into your Atlas account and navigate to the + :guilabel:`Clusters` section and click the :guilabel:`Connect` button + for your new deployment. + + .. figure:: /includes/figures/atlas_connection_connect_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. + + .. 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:: Edit your connection string credentials + + Paste your connection string into a file in your preferred text editor + and save this file to a safe location for later use. + Your connection string resembles the following example: + + .. code-block:: none + :copyable: false + + mongodb+srv://:@samplecluster.jkiff1s.mongodb.net/?retryWrites=true&w=majority&appName=SampleCluster + + Replace the ```` and ```` placeholders with + your database user's username and password. + + .. step:: Add a database to your connection string + + Specify a database connection in your connection string by adding + your database name after the hostname, as shown in the following example: + + .. code-block:: none + :copyable: false + + mongodb+srv://:@samplecluster.jkiff1s.mongodb.net/?retryWrites=true&w=majority&appName=SampleCluster + + Replace the ```` placeholder with ``sample_mflix`` to + configure a connection to the ``sample_mflix`` Atlas sample database. + +After completing these steps, you have a connection string that +contains your database username, database password, and database name. \ No newline at end of file diff --git a/source/get-started/create-admin.txt b/source/get-started/create-admin.txt new file mode 100644 index 0000000..70945fe --- /dev/null +++ b/source/get-started/create-admin.txt @@ -0,0 +1,130 @@ +.. _django-get-started-create-admin: + +==================== +Create an Admin Site +==================== + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :keywords: app, odm, code example + +You can create a Django admin site to edit your application's +data from a web interface. To learn more about the Django admin +site and its features, see `The Django admin site `__ +in the Django documentation. + +.. procedure:: + :style: connected + + .. step:: Create an admin user + + Before creating an admin site, you must create a user + who can log in to the site. + + From your project's root directory, run the following command to create + an admin user: + + .. code-block:: bash + + python manage.py createsuperuser + + Then, your terminal prompts you for a username, email address, + and password. For each prompt, enter the following information + to create a user with the specified credentials and press "enter" + after each entry: + + .. code-block:: bash + :copyable: false + + Username: admin + Email address: admin@example.com + Password: + Password (again): + + Replace the ```` placeholder with your user's password. + + .. step:: Enter the admin site + + Run the following code to start your server: + + .. code-block:: bash + + python manage.py runserver + + Once your server is running, visit the http://127.0.0.1:8000/admin/ + URL to see the admin site. This site displays the following login + screen: + + .. figure:: /includes/figures/django_admin_login.png + :alt: The login screen on the Django admin page. + + Enter the username and password created in the previous step to log in to + the site. + + .. step:: Access your "sample_mflix" app from the admin site + + After logging in to the admin site, you can see the following information: + + .. figure:: /includes/figures/django_admin_index.png + :alt: The initial content displayed on the Django admin site. + + You can edit your project's authentication configuration by selecting + the :guilabel:`Groups` or :guilabel:`Users` row in the + :guilabel:`Authentication and Authorization` table. + + To edit the data in the ``users`` sample collection, represented by your + ``Viewer`` model, navigate to your project's ``sample_mflix/admin.py`` file + and paste the following code: + + .. code-block:: python + + from django.contrib import admin + + from .models import Viewer + + admin.site.register(Viewer) + + Now, your admin site displays the following information: + + .. figure:: /includes/figures/django_admin_model.png + :alt: The content displayed on the Django admin site after registering a model. + + .. step:: Select a Viewer object + + You can view the data stored in a ``Viewer`` object that + has a ``name`` value of ``"Abigail Carter"``. You created + this object in the :ref:`django-get-started-write` step + of this tutorial. + + Click on the :guilabel:`Viewers` row of the :guilabel:`SAMPLE_MFLIX` + table to see a list of viewers. The admin site displays the following + list: + + .. figure:: /includes/figures/django_admin_viewers.png + :alt: The list of viewers displayed on the admin site. + + Then, click on :guilabel:`Abigail Carter` at the top of the list. + The site displays the :guilabel:`Name` and :guilabel:`Email` of + the selected viewer: + + .. figure:: /includes/figures/django_admin_edit_viewer.png + :alt: The information of your selected viewer. + + .. step:: Edit the data in a Viewer object + + To edit the ``email`` field of the viewer, select the + box that contains the text ``"abigail.carter@fakegmail.com"``. + Delete this text and replace it with ``"acarter1@fakegmail.com"``, + as shown in the following image: + + .. figure:: /includes/figures/django_admin_new_email.png + :alt: The updated email address of your viewer. + + Then, click the :guilabel:`SAVE` button below the viewer's + information to save your changes. + +After completing these steps, you can access the Django +admin site and use it to edit your ``Viewer`` objects. \ No newline at end of file diff --git a/source/get-started/create-app.txt b/source/get-started/create-app.txt new file mode 100644 index 0000000..8ab479a --- /dev/null +++ b/source/get-started/create-app.txt @@ -0,0 +1,147 @@ +.. _django-get-started-create-app: + +===================== +Create an Application +===================== + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :keywords: app, odm, code example + +In your ``quickstart`` project, you can create an application +that interacts with the Atlas sample database called ``sample_mflix``. +This database contains a ``movies`` collection, which stores +information about movies. The database also contains a ``users`` +collection, which stores information about movie viewers who use +a streaming service. + +To learn more about the ``sample_mflix`` database, see :atlas:`Sample Mflix Dataset +` in the Atlas documentation. + +.. procedure:: + :style: connected + + .. step:: Create a "sample_mflix" app + + From your project's root directory, run the following command to create a + new Django app called ``sample_mflix`` based on a custom template: + + .. code-block:: bash + + python manage.py startapp sample_mflix --template https://github.com/mongodb-labs/django-mongodb-app/archive/refs/heads/{+django-version+}.x.zip + + .. note:: App Template + + The ``django-mongodb-app`` template ensures that your ``app.py`` file + includes the line ``"default_auto_field = 'django_mongodb_backend.fields.ObjectIdAutoField'"``. + + .. step:: Create models for movie, awards, and viewer data + + Open the ``models.py`` file in the ``sample_mflix`` directory and replace + its contents with the following code: + + .. literalinclude:: /includes/get-started/models.py + :language: python + :copyable: + + The ``Movie`` model represents the ``sample_mflix.movies`` collection + and stores information about movies. This model contains an embedded + model field named ``awards``, which stores an ``Award`` object. The + model also contains an array field named ``genres``, which stores + a list of genres that describe the movie. + + The ``Award`` model does not represent a separate collection. Instead, it + represents the embedded document values stored in the ``Movie`` model. + + The ``Viewer`` model represents the ``sample_mflix.users`` collection + and stores account information for movie viewers. + + .. step:: Create views to display data + + Open the ``views.py`` file in your ``sample_mflix`` directory and replace + its contents with the following code: + + .. literalinclude:: /includes/get-started/views.py + :language: python + :copyable: + + These views display a landing page message and information about your ``Movie`` + and ``Viewer`` models. + + .. step:: Configure URLs for your views + + Create a new file called ``urls.py`` file in your ``sample_mflix`` directory. + To map the views defined in the preceding step to URLs, paste the following + code into ``urls.py``: + + .. literalinclude:: /includes/get-started/urls.py + :language: python + :copyable: + + 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("admin/", admin.site.urls), + path("", include("sample_mflix.urls")), + ] + + .. step:: Create templates to format your data + + In your ``sample_mflix`` directory, create a subdirectory called + ``templates``. Then, create a file called ``recent_movies.html`` + and paste the following code: + + .. literalinclude:: /includes/get-started/recent_movies.html + :language: html + :copyable: + + This template formats the movie data requested by the ``recent_movies`` view. + + Create another file in the ``sample_mflix/templates`` directory called + ``viewers_list.html`` and paste the following code: + + .. literalinclude:: /includes/get-started/viewers_list.html + :language: html + :copyable: + + This template formats the user data requested by the ``viewers_list`` view. + + .. 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 ``Movie``, ``Award``, and ``Viewer`` models and apply + the changes to the database: + + .. code-block:: bash + + python manage.py makemigrations sample_mflix + python manage.py migrate + +After completing these steps, you have a basic {+django-odm+} app that +you can use to access the ``sample_mflix`` Atlas database. \ No newline at end of file diff --git a/source/get-started/create-deployment.txt b/source/get-started/create-deployment.txt new file mode 100644 index 0000000..09cb2b3 --- /dev/null +++ b/source/get-started/create-deployment.txt @@ -0,0 +1,28 @@ +.. _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 ` + guide to set up a new Atlas account and a free tier MongoDB deployment. + Ensure that you **load sample data** and **add your IP address** to the IP access + list. + + .. 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. \ No newline at end of file diff --git a/source/get-started/install.txt b/source/get-started/install.txt new file mode 100644 index 0000000..a05fb32 --- /dev/null +++ b/source/get-started/install.txt @@ -0,0 +1,69 @@ +.. _django-get-started-download-and-install: + +==================== +Download and Install +==================== + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :keywords: setup, odm, code example + +Complete the following steps to install {+django-odm+} and its dependencies +in your development environment. + +.. procedure:: + :style: connected + + .. step:: Install the dependencies + + Before installing {+django-odm+}, ensure you have `Python 3.10 or later `__ + installed in your development environment. + + .. step:: Create a virtual environment + + Select the tab corresponding to your operating system and run the following commands + to create and activate a virtual environment in which to install {+django-odm+}: + + .. tabs:: + + .. tab:: macOS / Linux + :tabid: mac-linux-venv + + .. code-block:: bash + + python -m venv venv + source venv/bin/activate + + .. tab:: Windows + :tabid: windows-venv + + .. code-block:: bash + + python -m venv venv + . venv\Scripts\activate + + .. tip:: + + In the preceding commands, you might need to replace + ``python`` with the command that points to your Python + 3.10+ interpreter. + + .. step:: Install {+django-odm+} + + With the virtual environment activated, run the following command to install + the Django integration: + + .. code-block:: bash + + pip install django-mongodb-backend + + This command also installs the following dependencies: + + - PyMongo version {+pymongo-version+} and its dependencies + - Latest Django {+django-version+}.x version and its dependencies + +After you complete these steps, you have {+django-odm+} and its +dependencies installed in your development environment. \ No newline at end of file diff --git a/source/get-started/next-steps.txt b/source/get-started/next-steps.txt new file mode 100644 index 0000000..ffe2162 --- /dev/null +++ b/source/get-started/next-steps.txt @@ -0,0 +1,16 @@ +.. _django-get-started-next-steps: + +========== +Next Steps +========== + +Congratulations on completing the {+django-odm+} tutorial! + +In this tutorial, you created a Django application that +connects to a MongoDB deployment hosted on MongoDB Atlas +and interacts with data. + +Learn more about {+django-odm+} from the following resources: + +- :github:`django-mongodb-backend ` source code +- `{+django-odm+} <{+django-api+}>`__ API documentation \ No newline at end of file diff --git a/source/get-started/query-data.txt b/source/get-started/query-data.txt new file mode 100644 index 0000000..3e6f8e4 --- /dev/null +++ b/source/get-started/query-data.txt @@ -0,0 +1,74 @@ +.. _django-get-started-query: + +================== +Query MongoDB Data +================== + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :keywords: app, odm, code example + +You can import your models into the Python interactive shell +to read data from the ``sample_mflix`` database. + +.. procedure:: + :style: connected + + .. step:: Query the "users" collection for a specified email + + Start a Python shell by running the following command: + + .. code-block:: bash + + python manage.py shell + + Then, run the following code to query the + ``sample_mflix.users`` collection for a movie viewer whose email is + ``"jason_momoa@gameofthron.es"``: + + .. literalinclude:: /includes/get-started/read-write-data.py + :start-after: start-query-email + :end-before: end-query-email + :language: python + :copyable: + + This code returns the name of the matching user: + + .. code-block:: bash + :copyable: false + + + + .. step:: Query the "movies" collection for specified runtime values + + Run the following code to query the ``sample_mflix.movies`` + collection for movies that have a ``runtime`` value less than + ``10``: + + .. literalinclude:: /includes/get-started/read-write-data.py + :start-after: start-query-runtime + :end-before: end-query-runtime + :language: python + :copyable: + + This code returns a truncated list of the matching movies: + + .. code-block:: bash + :copyable: false + + , , , , , + , , , + , , , + , , + , , + , , + , , + , '...(remaining elements truncated)...']> + +After completing this step, you can run queries on data stored in +your MongoDB deployment. \ No newline at end of file diff --git a/source/get-started/write-data.txt b/source/get-started/write-data.txt new file mode 100644 index 0000000..b9e9a11 --- /dev/null +++ b/source/get-started/write-data.txt @@ -0,0 +1,121 @@ +.. _django-get-started-write: + +===================== +Write Data to MongoDB +===================== + +.. facet:: + :name: genre + :values: tutorial + +.. meta:: + :keywords: app, odm, code example + +You can use your application's models to update documents +stored in the ``sample_mflix`` database. To update documents, +enter the Python interactive shell and call create, update, +and delete functions on your model objects. + +.. procedure:: + :style: connected + + .. step:: Start a Python shell + + From your project's root directory, run the following command to + enter the Python shell: + + .. code-block:: bash + + python manage.py shell + + .. step:: Import the required classes and modules + + From your Python shell, run the following code to import + your models and the module for creating a ``datetime`` object: + + .. literalinclude:: /includes/get-started/read-write-data.py + :start-after: start-imports + :end-before: end-imports + :language: python + :copyable: + + .. step:: Insert a movie into the database + + Run the following code to create an ``Movie`` object that + stores data about a movie titled ``"Minari"``, including + its awards in an ``Award`` object: + + .. literalinclude:: /includes/get-started/read-write-data.py + :start-after: start-insert-movie + :end-before: end-insert-movie + :language: python + :copyable: + + .. step:: Update your Movie object + + The ``Movie`` object created in the previous step has inaccurate data: + the ``runtime`` value is ``217``, but the correct ``runtime`` value is ``117``. + + Run the following code to update the object's ``runtime`` value: + + .. literalinclude:: /includes/get-started/read-write-data.py + :start-after: start-update-movie + :end-before: end-update-movie + :language: python + :copyable: + + .. step:: Insert a Viewer into the database + + You can also use your ``Viewer`` model to insert documents into the + ``sample_mflix.users`` collection. Run the following code to create + a ``Viewer`` object that stores data about a movie viewer named ``"Abigail Carter"``: + + .. literalinclude:: /includes/get-started/read-write-data.py + :start-after: start-insert-viewer + :end-before: end-insert-viewer + :language: python + :copyable: + + .. step:: Delete a Viewer object + + One movie viewer named "Alliser Thorne" no longer uses the movie streaming + site. To remove this viewer's corresponding document from the database, + run the following code: + + .. literalinclude:: /includes/get-started/read-write-data.py + :start-after: start-delete-viewer + :end-before: end-delete-viewer + :language: python + :copyable: + + .. step:: Start the development server + + Exit the Python shell by running the following code: + + .. code-block:: python + + exit() + + Then, start your server by running the following command + from your project's root directory: + + .. code-block:: bash + + python manage.py runserver + + .. step:: Render your new objects + + To ensure that you inserted a ``Movie`` object into the database, + visit the http://127.0.0.1:8000/recent_movies/ URL. + You can see a list of five movies in the ``sample_mflix.movies`` + database, with your new movie listed at the top. + + Then, ensure that you inserted a ``Viewer`` object into the + database by visiting the http://127.0.0.1:8000/viewers_list/ + URL. You can see a list of ten viewer names in the ``sample_mflix.users`` + database, with your new viewer listed at the top. Ensure that the + viewer named "Alliser Thorne", deleted in a previous step, does not appear + in this list. + +After completing these steps, you have inserted and edited documents +in the ``sample_mflix`` sample database. \ No newline at end of file diff --git a/source/includes/figures/atlas_connection_connect_cluster.png b/source/includes/figures/atlas_connection_connect_cluster.png new file mode 100644 index 0000000..dce8a0d Binary files /dev/null and b/source/includes/figures/atlas_connection_connect_cluster.png differ diff --git a/source/includes/figures/atlas_connection_copy_string_python.png b/source/includes/figures/atlas_connection_copy_string_python.png new file mode 100644 index 0000000..7796cab Binary files /dev/null and b/source/includes/figures/atlas_connection_copy_string_python.png differ diff --git a/source/includes/figures/django_admin_edit_viewer.png b/source/includes/figures/django_admin_edit_viewer.png new file mode 100644 index 0000000..fde39d1 Binary files /dev/null and b/source/includes/figures/django_admin_edit_viewer.png differ diff --git a/source/includes/figures/django_admin_index.png b/source/includes/figures/django_admin_index.png new file mode 100644 index 0000000..9df6dd2 Binary files /dev/null and b/source/includes/figures/django_admin_index.png differ diff --git a/source/includes/figures/django_admin_login.png b/source/includes/figures/django_admin_login.png new file mode 100644 index 0000000..498184a Binary files /dev/null and b/source/includes/figures/django_admin_login.png differ diff --git a/source/includes/figures/django_admin_model.png b/source/includes/figures/django_admin_model.png new file mode 100644 index 0000000..7e8345d Binary files /dev/null and b/source/includes/figures/django_admin_model.png differ diff --git a/source/includes/figures/django_admin_new_email.png b/source/includes/figures/django_admin_new_email.png new file mode 100644 index 0000000..c3891a7 Binary files /dev/null and b/source/includes/figures/django_admin_new_email.png differ diff --git a/source/includes/figures/django_admin_viewers.png b/source/includes/figures/django_admin_viewers.png new file mode 100644 index 0000000..8c3540f Binary files /dev/null and b/source/includes/figures/django_admin_viewers.png differ diff --git a/source/includes/get-started/models.py b/source/includes/get-started/models.py new file mode 100644 index 0000000..6a221cf --- /dev/null +++ b/source/includes/get-started/models.py @@ -0,0 +1,38 @@ +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 Meta: + managed = False + +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 \ No newline at end of file diff --git a/source/includes/get-started/read-write-data.py b/source/includes/get-started/read-write-data.py new file mode 100644 index 0000000..3266f3b --- /dev/null +++ b/source/includes/get-started/read-write-data.py @@ -0,0 +1,44 @@ +# start-imports +from sample_mflix.models import Movie, Award, Viewer +from django.utils import timezone +from datetime import datetime +# end-imports + +# start-insert-movie +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"] +) +# end-insert-movie + +# start-update-movie +movie.runtime = 117 +movie.save() +# end-update-movie + +# start-insert-viewer +viewer = Viewer.objects.create( + name="Abigail Carter", + email="abigail.carter@fakegmail.com" +) +# end-insert-viewer + +# start-delete-viewer +old_viewer = Viewer.objects.filter(name="Alliser Thorne").first() +old_viewer.delete() +# end-delete-viewer + +# start-query-email +from sample_mflix.models import Movie, Viewer + +Viewer.objects.filter(email="jason_momoa@gameofthron.es").first() +# end-query-email + +# start-query-runtime +Movie.objects.filter(runtime__lt=10) +# end-query-runtime \ No newline at end of file diff --git a/source/includes/get-started/recent_movies.html b/source/includes/get-started/recent_movies.html new file mode 100644 index 0000000..bc67e8d --- /dev/null +++ b/source/includes/get-started/recent_movies.html @@ -0,0 +1,21 @@ + + + + + + + Recent Movies + + +

Five Most Recent Movies

+
    + {% for movie in movies %} +
  • + {{ movie.title }} (Released: {{ movie.released }}) +
  • + {% empty %} +
  • No movies found.
  • + {% endfor %} +
+ + \ No newline at end of file diff --git a/source/includes/get-started/urls.py b/source/includes/get-started/urls.py new file mode 100644 index 0000000..55d60f5 --- /dev/null +++ b/source/includes/get-started/urls.py @@ -0,0 +1,9 @@ +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"), +] \ No newline at end of file diff --git a/source/includes/get-started/viewers_list.html b/source/includes/get-started/viewers_list.html new file mode 100644 index 0000000..764d715 --- /dev/null +++ b/source/includes/get-started/viewers_list.html @@ -0,0 +1,32 @@ + + + + + + + Viewers List + + +

Alphabetical Viewers List

+ + + + + + + + + {% for viewer in viewers %} + + + + + {% empty %} + + + + {% endfor %} + +
NameEmail
{{ viewer.name }}{{ viewer.email }}
No viewer found.
+ + \ No newline at end of file diff --git a/source/includes/get-started/views.py b/source/includes/get-started/views.py new file mode 100644 index 0000000..d782dbd --- /dev/null +++ b/source/includes/get-started/views.py @@ -0,0 +1,15 @@ +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}) \ No newline at end of file diff --git a/source/index.txt b/source/index.txt index 12afc87..68ae634 100644 --- a/source/index.txt +++ b/source/index.txt @@ -11,13 +11,12 @@ Django MongoDB Backend .. toctree:: + Get Started Interact with Data Issues & Help Compatibility - .. TODO: - Get Started Connection Configuration Model Your Data Django Feature Limitations @@ -29,6 +28,12 @@ Introduction Welcome to the documentation site for the official {+django-odm+}, a Django database backend that uses PyMongo to connect to MongoDB. +Get Started +----------- + +Learn how to install {+django-odm+}, establish a connection to MongoDB, and begin +working with data in the :ref:`django-get-started` tutorial. + Interact with Data ------------------ @@ -37,12 +42,6 @@ in the :ref:`django-interact-data` section. .. TODO: -.. Get Started -.. ----------- - -.. Learn how to install {+django-odm+}, establish a connection to MongoDB, and begin - working with data in the :ref:`django-get-started` tutorial. - .. Connect to MongoDB .. ------------------