Skip to content

Commit 6b599a7

Browse files
committed
admin site, more crud operations
1 parent f2b7d40 commit 6b599a7

12 files changed

+246
-67
lines changed

snooty.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ sharedinclude_root = "https://raw.githubusercontent.com/10gen/docs-shared/main/"
2626
driver-short = "PyMongo"
2727
driver-long = "PyMongo, the MongoDB synchronous Python driver,"
2828
driver-async = "PyMongo Async"
29-
django-odm = "Django MongoDB"
29+
django-odm = "MongoDB Backend for Django"
3030
language = "Python"
3131
mdb-server = "MongoDB Server"
3232
mongo-community = "MongoDB Community Edition"

source/django-get-started.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ Get Started with {+django-odm+}
2727
Create an Application </django-get-started/django-create-app/>
2828
Write Data to MongoDB </django-get-started/django-write-data/>
2929
Query MongoDB Data </django-get-started/django-query-data/>
30+
Create an Admin Site </django-get-started/django-create-admin/>
3031
Next Steps </django-get-started/django-next-steps/>
3132

3233
{+django-odm+} is a PyMongo integration that allows you to use the
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
.. _django-get-started-create-admin:
2+
3+
====================
4+
Create an Admin Site
5+
====================
6+
7+
.. facet::
8+
:name: genre
9+
:values: tutorial
10+
11+
.. meta::
12+
:keywords: app, odm, code example
13+
14+
You can create a Django admin site to edit your application's
15+
data from a web interface. To learn more about the Django admin
16+
site and its features, see `The Django admin site <https://docs.djangoproject.com/en/5.1/ref/contrib/admin/>`__
17+
in the Django documentation.
18+
19+
.. procedure::
20+
:style: connected
21+
22+
.. step:: Create an admin user
23+
24+
Before creating an admin site, you must create a user
25+
who can log in to the site.
26+
27+
From your project's root directory, run the following command to create
28+
an admin user:
29+
30+
.. code-block:: bash
31+
32+
python3 manage.py createsuperuser
33+
34+
Then, your terminal prompts you for a username, email address,
35+
and password. For each prompt, enter the following information
36+
to create a user with the specified credentials and press "enter"
37+
after each entry:
38+
39+
.. code-block:: bash
40+
41+
Username: admin
42+
Email address: [email protected]
43+
Password: <admin-password>
44+
Password (again): <admin-password>
45+
46+
Replace the ``<admin-password>`` placeholder with your user's password.
47+
48+
.. step:: Enter the admin site
49+
50+
Run the following code to start your server:
51+
52+
.. code-block:: bash
53+
54+
python3 manage.py runserver
55+
56+
Once your server is running, visit the http://127.0.0.1:8000/admin/
57+
URL to see the admin site. This site displays the following login
58+
screen:
59+
60+
.. figure:: /includes/figures/django_admin_login.png
61+
:alt: The login screen on the Django admin page.
62+
63+
Enter the username and password created in the previous step to log in to
64+
the site.
65+
66+
.. step:: Access your sample_mflix app from the admin site
67+
68+
After logging in to the admin site, you can see the following index
69+
page:
70+
71+
.. figure:: /includes/figures/django_admin_index.png
72+
:alt: The initial content displayed on the Django admin site.
73+
74+
You can edit your project's authentication configuration by selecting
75+
the :guilabel:`Groups` or :guilabel:`Users` row in the
76+
:guilabel:`Authentication and Authorization` table.
77+
78+
To edit the data in the ``users`` sample collection, represented by your
79+
``Viewer`` model, navigate to your project's ``sample_mflix/admin.py`` file
80+
and paste the following code:
81+
82+
.. code-block:: python
83+
84+
from django.contrib import admin
85+
86+
from .models import Viewer
87+
88+
admin.site.register(Viewer)
89+
90+
Now, your admin site displays the following information:
91+
92+
.. figure:: /includes/figures/django_admin_model.png
93+
:alt: The content displayed on the Django admin site after registering a model.
94+
95+
.. step:: Select a Viewer object
96+
97+
You can view the data stored in a ``Viewer`` object that
98+
has a ``name`` value of ``"Abigail Carter"``. You created
99+
this object in the :ref:`django-get-started-write` step
100+
of this tutorial.
101+
102+
Click on the :guilabel:`Viewers` row of the :guilabel:`SAMPLE_MFLIX`
103+
table to see a list of viewers. The admin site displays the following
104+
list:
105+
106+
.. figure:: /includes/figures/django_admin_viewers.png
107+
:alt: The list of viewers displayed on the admin site.
108+
109+
Then, click on :guilabel:`Abigail Carter` at the top of the list.
110+
The site displays the :guilabel:`Name`, :guilabel:`Email`, and :guilabel:`Password`
111+
of the selected viewer:
112+
113+
.. figure:: /includes/figures/django_admin_edit_viewer.png
114+
:alt: The information of your selected viewer.
115+
116+
.. step:: Edit the data in a Viewer object
117+
118+
To edit the ``email`` field of the viewer, select the
119+
box that contains the text ``"[email protected]"``.
120+
Delete this text and replace it with ``"[email protected]"``,
121+
as shown in the following image:
122+
123+
.. figure:: /includes/figures/django_admin_new_email.png
124+
:alt: The updated email address of your viewer.
125+
126+
Then, click the :guilabel:`SAVE` button below the viewer's
127+
information to save your changes.
128+
129+
After completing these steps, you can access the Django
130+
admin site and use it to edit your ``Viewer`` objects.

source/django-get-started/django-create-app.txt

Lines changed: 45 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -28,45 +28,61 @@ Create an Application
2828
The ``django-mongodb-app`` template ensures that your ``app.py`` file
2929
includes the line ``"default_auto_field = 'django_mongodb.fields.ObjectIdAutoField'"``.
3030

31-
.. step:: Create models for movie and user data
31+
.. step:: Create models for movie, awards, and viewer data
3232

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

3636
.. code-block:: python
3737

3838
from django.db import models
39+
from django_mongodb.fields import EmbeddedModelField, ArrayField
3940

40-
class Movies(models.Model):
41+
class Movie(models.Model):
4142
title = models.CharField(max_length=200)
4243
plot = models.TextField(null=True)
4344
runtime = models.IntegerField(default=0)
4445
released = models.DateTimeField("release date", null=True)
46+
awards = EmbeddedModelField(Award)
47+
genres = ArrayField(models.CharField(max_length=100), blank=True)
4548

4649
class Meta:
47-
managed = False
4850
db_table = "movies"
4951

5052
def __str__(self):
5153
return self.title
54+
55+
class Award(models.Model):
56+
wins = models.IntegerField(default=0)
57+
nominations = models.IntegerField(default=0)
58+
text = models.CharField(max_length=100)
5259

60+
class Meta:
61+
abstract = True
5362

54-
class Users(models.Model):
63+
class Viewer(models.Model):
5564
name = models.CharField(max_length=100)
5665
email = models.CharField(max_length=200)
5766
password = models.CharField(max_length=100)
5867

5968
class Meta:
60-
managed = False
6169
db_table = "users"
6270

6371
def __str__(self):
6472
return self.name
6573

66-
The ``Movies`` model represents the ``sample_mflix.movies`` collection
67-
and stores information about movies. The ``Users`` model represents
68-
the ``sample_mflix.users`` collection and stores account credentials
69-
for users of a movie streaming platform.
74+
The ``Movie`` model represents the ``sample_mflix.movies`` collection
75+
and stores information about movies. This model contains an embedded
76+
model field named ``awards``, which stores an ``Award`` object. The
77+
model also contains an array field named ``genres``, which stores
78+
a list of genres that describe the movie.
79+
80+
The ``Award`` model does not represent a separate collection. Instead, it
81+
represents the embedded document values that the ``awards``
82+
field of the ``Movie`` model stores.
83+
84+
The ``Viewer`` model represents the ``sample_mflix.users`` collection
85+
and stores account credentials for movie viewers.
7086

7187
.. step:: Create views to display data
7288

@@ -78,21 +94,22 @@ Create an Application
7894
from django.http import HttpResponse
7995
from django.shortcuts import render
8096

81-
from .models import Movies, Users
97+
from .models import Movie, Viewer
8298

8399
def index(request):
84-
return HttpResponse("Hello! You've reached the Django MongoDB sample app landing page.")
100+
return HttpResponse("Hello, world. You're at the application index.")
101+
85102

86103
def recent_movies(request):
87-
movies = Movies.objects.all().order_by('-released')[:5]
104+
movies = Movie.objects.all().order_by('-released')[:5]
88105
return render(request, 'recent_movies.html', {'movies': movies})
89106

90-
def users_list(request):
91-
users = Users.objects.all().order_by('name')[:10]
92-
return render(request, 'users_list.html', {'users': users})
107+
def viewers_list(request):
108+
viewers = Viewer.objects.all().order_by('name')[:10]
109+
return render(request, 'viewers_list.html', {'viewers': viewers})
93110

94-
These views display a landing page message and information about your ``Movies``
95-
and ``Users`` models.
111+
These views display a landing page message and information about your ``Movie``
112+
and ``Viewer`` models.
96113

97114
.. step:: Configure URLs for your views
98115

@@ -109,7 +126,7 @@ Create an Application
109126
urlpatterns = [
110127
path("", views.index, name="index"),
111128
path('recent_movies/', views.recent_movies, name='recent_movies'),
112-
path('users_list/', views.users_list, name='users_list'),
129+
path('viewers_list/', views.viewers_list, name='viewers_list'),
113130
]
114131

115132
Then, navigate to the ``quickstart/urls.py`` file and replace its contents with
@@ -158,20 +175,20 @@ Create an Application
158175
This template formats the movie data requested by the ``recent_movies`` view.
159176

160177
Create another file in the ``sample_mflix/templates`` directory called
161-
``users_list.html`` and paste the following code:
178+
``viewers_list.html`` and paste the following code:
162179

163180
.. code-block:: python
164181

165-
<!-- templates/users_list.html -->
182+
<!-- templates/viewers_list.html -->
166183
<!DOCTYPE html>
167184
<html lang="en">
168185
<head>
169186
<meta charset="UTF-8">
170187
<meta name="viewport" content="width=device-width, initial-scale=1.0">
171-
<title>Users List</title>
188+
<title>Viewers List</title>
172189
</head>
173190
<body>
174-
<h1>Alphabetical Users List</h1>
191+
<h1>Alphabetical Viewers List</h1>
175192
<table>
176193
<thead>
177194
<tr>
@@ -180,22 +197,22 @@ Create an Application
180197
</tr>
181198
</thead>
182199
<tbody>
183-
{% for user in users %}
200+
{% for viewer in viewers %}
184201
<tr>
185-
<td>{{ user.name }}</td>
186-
<td>{{ user.email }}</td>
202+
<td>{{ viewer.name }}</td>
203+
<td>{{ viewer.email }}</td>
187204
</tr>
188205
{% empty %}
189206
<tr>
190-
<td colspan="2">No users found.</td>
207+
<td colspan="2">No viewer found.</td>
191208
</tr>
192209
{% endfor %}
193210
</tbody>
194211
</table>
195212
</body>
196213
</html>
197214

198-
This template formats the user data requested by the ``users_list`` view.
215+
This template formats the user data requested by the ``viewers_list`` view.
199216

200217
.. step:: Include your app in your project
201218

@@ -217,7 +234,7 @@ Create an Application
217234
.. step:: Create migrations for your new models
218235

219236
From your project root, run the following command to create
220-
migrations for the ``Movies`` and ``Users`` models and apply
237+
migrations for the ``Movie``, ``Award``, and ``Viewer`` models and apply
221238
the changes to the database:
222239

223240
.. code-block:: bash

source/django-get-started/django-query-data.txt

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -16,21 +16,24 @@ Query MongoDB Data
1616

1717
.. step:: Query the users collection for a specified email
1818

19-
From the same Python shell as the :ref:`django-get-started-write`
20-
step of this tutorial, run the following code to query the
21-
``sample_mflix.users`` collection for a user whose email is
19+
Start a Python shell and include the required imports
20+
by running the following code:
21+
22+
23+
Then, run the following code to query the
24+
``sample_mflix.users`` collection for a movie viewer whose email is
2225
2326

2427
.. code-block:: bash
2528

26-
Users.objects.filter(email="[email protected]").first()
29+
Viewer.objects.filter(email="[email protected]").first()
2730

2831
This code returns the name of the matching user:
2932

3033
.. code-block:: bash
3134
:copyable: false
3235

33-
<QuerySet [<Users: Khal Drogo>]>
36+
<QuerySet [<Viewer: Khal Drogo>]>
3437

3538
.. step:: Query the movies collection for runtime values
3639

@@ -40,23 +43,23 @@ Query MongoDB Data
4043

4144
.. code-block:: bash
4245

43-
Movies.objects.filter(runtime__lt=10)
46+
Movie.objects.filter(runtime__lt=10)
4447

4548
This code returns a truncated list of the matching movies:
4649

4750
.. code-block:: bash
4851
:copyable: false
4952

50-
<QuerySet [<Movies: Winsor McCay, the Famous Cartoonist of the N.Y.
51-
Herald and His Moving Comics>, <Movies: Steamboat Willie>, <Movies:
52-
Three Little Pigs>, <Movies: The Band Concert>, <Movies: Who Killed Cock Robin?>,
53-
<Movies: Dots>, <Movies: The Cat Concerto>, <Movies: Begone Dull Care>,
54-
<Movies: Mi adorado Juan>, <Movies: Neighbours>, <Movies: A Phantasy>,
55-
<Movies: Duck Amuck>, <Movies: Duck Dodgers in the 24èth Century>,
56-
<Movies: Blinkity Blank>, <Movies: One Froggy Evening>,
57-
<Movies: What's Opera, Doc?>, <Movies: Lines: Horizontal>,
58-
<Movies: Il fornaretto di Venezia>, <Movies: Dog Star Man: Part IV>,
59-
<Movies: Now>, '...(remaining elements truncated)...']>
53+
<QuerySet [<Movie: Winsor McCay, the Famous Cartoonist of the N.Y.
54+
Herald and His Moving Comics>, <Movie: Steamboat Willie>, <Movie:
55+
Three Little Pigs>, <Movie: The Band Concert>, <Movie: Who Killed Cock Robin?>,
56+
<Movie: Dots>, <Movie: The Cat Concerto>, <Movie: Begone Dull Care>,
57+
<Movie: Mi adorado Juan>, <Movie: Neighbours>, <Movie: A Phantasy>,
58+
<Movie: Duck Amuck>, <Movie: Duck Dodgers in the 24èth Century>,
59+
<Movie: Blinkity Blank>, <Movie: One Froggy Evening>,
60+
<Movie: What's Opera, Doc?>, <Movie: Lines: Horizontal>,
61+
<Movie: Il fornaretto di Venezia>, <Movie: Dog Star Man: Part IV>,
62+
<Movie: Now>, '...(remaining elements truncated)...']>
6063

6164
After completing this step, you can run queries on data stored in
6265
your MongoDB deployment.

0 commit comments

Comments
 (0)