tutorial02.txt 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. =====================================
  2. Writing your first Django app, part 2
  3. =====================================
  4. This tutorial begins where :doc:`Tutorial 1 </intro/tutorial01>` left off.
  5. We'll set up the database, create your first model, and get a quick
  6. introduction to Django's automatically-generated admin site.
  7. .. admonition:: Where to get help:
  8. If you're having trouble going through this tutorial, please head over to
  9. the :doc:`Getting Help</faq/help>` section of the FAQ.
  10. Database setup
  11. ==============
  12. Now, open up :file:`mysite/settings.py`. It's a normal Python module with
  13. module-level variables representing Django settings.
  14. By default, the :setting:`DATABASES` configuration uses SQLite. If you're new
  15. to databases, or you're just interested in trying Django, this is the easiest
  16. choice. SQLite is included in Python, so you won't need to install anything
  17. else to support your database. When starting your first real project, however,
  18. you may want to use a more scalable database like PostgreSQL, to avoid
  19. database-switching headaches down the road.
  20. If you wish to use another database, see :ref:`details to customize and get
  21. your database running <database-installation>`.
  22. While you're editing :file:`mysite/settings.py`, set :setting:`TIME_ZONE` to
  23. your time zone.
  24. Also, note the :setting:`INSTALLED_APPS` setting at the top of the file. That
  25. holds the names of all Django applications that are activated in this Django
  26. instance. Apps can be used in multiple projects, and you can package and
  27. distribute them for use by others in their projects.
  28. By default, :setting:`INSTALLED_APPS` contains the following apps, all of which
  29. come with Django:
  30. * :mod:`django.contrib.admin` -- The admin site. You'll use it shortly.
  31. * :mod:`django.contrib.auth` -- An authentication system.
  32. * :mod:`django.contrib.contenttypes` -- A framework for content types.
  33. * :mod:`django.contrib.sessions` -- A session framework.
  34. * :mod:`django.contrib.messages` -- A messaging framework.
  35. * :mod:`django.contrib.staticfiles` -- A framework for managing
  36. static files.
  37. These applications are included by default as a convenience for the common case.
  38. Some of these applications make use of at least one database table, though,
  39. so we need to create the tables in the database before we can use them. To do
  40. that, run the following command:
  41. .. console::
  42. $ python manage.py migrate
  43. The :djadmin:`migrate` command looks at the :setting:`INSTALLED_APPS` setting
  44. and creates any necessary database tables according to the database settings
  45. in your :file:`mysite/settings.py` file and the database migrations shipped
  46. with the app (we'll cover those later). You'll see a message for each
  47. migration it applies. If you're interested, run the command-line client for your
  48. database and type ``\dt`` (PostgreSQL), ``SHOW TABLES;`` (MariaDB, MySQL),
  49. ``.tables`` (SQLite), or ``SELECT TABLE_NAME FROM USER_TABLES;`` (Oracle) to
  50. display the tables Django created.
  51. .. admonition:: For the minimalists
  52. Like we said above, the default applications are included for the common
  53. case, but not everybody needs them. If you don't need any or all of them,
  54. feel free to comment-out or delete the appropriate line(s) from
  55. :setting:`INSTALLED_APPS` before running :djadmin:`migrate`. The
  56. :djadmin:`migrate` command will only run migrations for apps in
  57. :setting:`INSTALLED_APPS`.
  58. .. _creating-models:
  59. Creating models
  60. ===============
  61. Now we'll define your models -- essentially, your database layout, with
  62. additional metadata.
  63. .. admonition:: Philosophy
  64. A model is the single, definitive source of information about your data. It
  65. contains the essential fields and behaviors of the data you're storing.
  66. Django follows the :ref:`DRY Principle <dry>`. The goal is to define your
  67. data model in one place and automatically derive things from it.
  68. This includes the migrations - unlike in Ruby On Rails, for example, migrations
  69. are entirely derived from your models file, and are essentially a
  70. history that Django can roll through to update your database schema to
  71. match your current models.
  72. In our poll app, we'll create two models: ``Question`` and ``Choice``. A
  73. ``Question`` has a question and a publication date. A ``Choice`` has two
  74. fields: the text of the choice and a vote tally. Each ``Choice`` is associated
  75. with a ``Question``.
  76. These concepts are represented by Python classes. Edit the
  77. :file:`polls/models.py` file so it looks like this:
  78. .. code-block:: python
  79. :caption: ``polls/models.py``
  80. from django.db import models
  81. class Question(models.Model):
  82. question_text = models.CharField(max_length=200)
  83. pub_date = models.DateTimeField("date published")
  84. class Choice(models.Model):
  85. question = models.ForeignKey(Question, on_delete=models.CASCADE)
  86. choice_text = models.CharField(max_length=200)
  87. votes = models.IntegerField(default=0)
  88. Here, each model is represented by a class that subclasses
  89. :class:`django.db.models.Model`. Each model has a number of class variables,
  90. each of which represents a database field in the model.
  91. Each field is represented by an instance of a :class:`~django.db.models.Field`
  92. class -- e.g., :class:`~django.db.models.CharField` for character fields and
  93. :class:`~django.db.models.DateTimeField` for datetimes. This tells Django what
  94. type of data each field holds.
  95. The name of each :class:`~django.db.models.Field` instance (e.g.
  96. ``question_text`` or ``pub_date``) is the field's name, in machine-friendly
  97. format. You'll use this value in your Python code, and your database will use
  98. it as the column name.
  99. You can use an optional first positional argument to a
  100. :class:`~django.db.models.Field` to designate a human-readable name. That's used
  101. in a couple of introspective parts of Django, and it doubles as documentation.
  102. If this field isn't provided, Django will use the machine-readable name. In this
  103. example, we've only defined a human-readable name for ``Question.pub_date``.
  104. For all other fields in this model, the field's machine-readable name will
  105. suffice as its human-readable name.
  106. Some :class:`~django.db.models.Field` classes have required arguments.
  107. :class:`~django.db.models.CharField`, for example, requires that you give it a
  108. :attr:`~django.db.models.CharField.max_length`. That's used not only in the
  109. database schema, but in validation, as we'll soon see.
  110. A :class:`~django.db.models.Field` can also have various optional arguments; in
  111. this case, we've set the :attr:`~django.db.models.Field.default` value of
  112. ``votes`` to 0.
  113. Finally, note a relationship is defined, using
  114. :class:`~django.db.models.ForeignKey`. That tells Django each ``Choice`` is
  115. related to a single ``Question``. Django supports all the common database
  116. relationships: many-to-one, many-to-many, and one-to-one.
  117. Activating models
  118. =================
  119. That small bit of model code gives Django a lot of information. With it, Django
  120. is able to:
  121. * Create a database schema (``CREATE TABLE`` statements) for this app.
  122. * Create a Python database-access API for accessing ``Question`` and ``Choice`` objects.
  123. But first we need to tell our project that the ``polls`` app is installed.
  124. .. admonition:: Philosophy
  125. Django apps are "pluggable": You can use an app in multiple projects, and
  126. you can distribute apps, because they don't have to be tied to a given
  127. Django installation.
  128. To include the app in our project, we need to add a reference to its
  129. configuration class in the :setting:`INSTALLED_APPS` setting. The
  130. ``PollsConfig`` class is in the :file:`polls/apps.py` file, so its dotted path
  131. is ``'polls.apps.PollsConfig'``. Edit the :file:`mysite/settings.py` file and
  132. add that dotted path to the :setting:`INSTALLED_APPS` setting. It'll look like
  133. this:
  134. .. code-block:: python
  135. :caption: ``mysite/settings.py``
  136. INSTALLED_APPS = [
  137. "polls.apps.PollsConfig",
  138. "django.contrib.admin",
  139. "django.contrib.auth",
  140. "django.contrib.contenttypes",
  141. "django.contrib.sessions",
  142. "django.contrib.messages",
  143. "django.contrib.staticfiles",
  144. ]
  145. Now Django knows to include the ``polls`` app. Let's run another command:
  146. .. console::
  147. $ python manage.py makemigrations polls
  148. You should see something similar to the following:
  149. .. code-block:: text
  150. Migrations for 'polls':
  151. polls/migrations/0001_initial.py
  152. + Create model Question
  153. + Create model Choice
  154. By running ``makemigrations``, you're telling Django that you've made
  155. some changes to your models (in this case, you've made new ones) and that
  156. you'd like the changes to be stored as a *migration*.
  157. Migrations are how Django stores changes to your models (and thus your
  158. database schema) - they're files on disk. You can read the migration for your
  159. new model if you like; it's the file ``polls/migrations/0001_initial.py``.
  160. Don't worry, you're not expected to read them every time Django makes one, but
  161. they're designed to be human-editable in case you want to manually tweak how
  162. Django changes things.
  163. There's a command that will run the migrations for you and manage your database
  164. schema automatically - that's called :djadmin:`migrate`, and we'll come to it in a
  165. moment - but first, let's see what SQL that migration would run. The
  166. :djadmin:`sqlmigrate` command takes migration names and returns their SQL:
  167. .. console::
  168. $ python manage.py sqlmigrate polls 0001
  169. You should see something similar to the following (we've reformatted it for
  170. readability):
  171. .. code-block:: sql
  172. BEGIN;
  173. --
  174. -- Create model Question
  175. --
  176. CREATE TABLE "polls_question" (
  177. "id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
  178. "question_text" varchar(200) NOT NULL,
  179. "pub_date" timestamp with time zone NOT NULL
  180. );
  181. --
  182. -- Create model Choice
  183. --
  184. CREATE TABLE "polls_choice" (
  185. "id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
  186. "choice_text" varchar(200) NOT NULL,
  187. "votes" integer NOT NULL,
  188. "question_id" bigint NOT NULL
  189. );
  190. ALTER TABLE "polls_choice"
  191. ADD CONSTRAINT "polls_choice_question_id_c5b4b260_fk_polls_question_id"
  192. FOREIGN KEY ("question_id")
  193. REFERENCES "polls_question" ("id")
  194. DEFERRABLE INITIALLY DEFERRED;
  195. CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");
  196. COMMIT;
  197. Note the following:
  198. * The exact output will vary depending on the database you are using. The
  199. example above is generated for PostgreSQL.
  200. * Table names are automatically generated by combining the name of the app
  201. (``polls``) and the lowercase name of the model -- ``question`` and
  202. ``choice``. (You can override this behavior.)
  203. * Primary keys (IDs) are added automatically. (You can override this, too.)
  204. * By convention, Django appends ``"_id"`` to the foreign key field name.
  205. (Yes, you can override this, as well.)
  206. * The foreign key relationship is made explicit by a ``FOREIGN KEY``
  207. constraint. Don't worry about the ``DEFERRABLE`` parts; it's telling
  208. PostgreSQL to not enforce the foreign key until the end of the transaction.
  209. * It's tailored to the database you're using, so database-specific field types
  210. such as ``auto_increment`` (MySQL), ``bigint PRIMARY KEY GENERATED BY DEFAULT
  211. AS IDENTITY`` (PostgreSQL), or ``integer primary key autoincrement`` (SQLite)
  212. are handled for you automatically. Same goes for the quoting of field names
  213. -- e.g., using double quotes or single quotes.
  214. * The :djadmin:`sqlmigrate` command doesn't actually run the migration on your
  215. database - instead, it prints it to the screen so that you can see what SQL
  216. Django thinks is required. It's useful for checking what Django is going to
  217. do or if you have database administrators who require SQL scripts for
  218. changes.
  219. If you're interested, you can also run
  220. :djadmin:`python manage.py check <check>`; this checks for any problems in
  221. your project without making migrations or touching the database.
  222. Now, run :djadmin:`migrate` again to create those model tables in your database:
  223. .. console::
  224. $ python manage.py migrate
  225. Operations to perform:
  226. Apply all migrations: admin, auth, contenttypes, polls, sessions
  227. Running migrations:
  228. Rendering model states... DONE
  229. Applying polls.0001_initial... OK
  230. The :djadmin:`migrate` command takes all the migrations that haven't been
  231. applied (Django tracks which ones are applied using a special table in your
  232. database called ``django_migrations``) and runs them against your database -
  233. essentially, synchronizing the changes you made to your models with the schema
  234. in the database.
  235. Migrations are very powerful and let you change your models over time, as you
  236. develop your project, without the need to delete your database or tables and
  237. make new ones - it specializes in upgrading your database live, without
  238. losing data. We'll cover them in more depth in a later part of the tutorial,
  239. but for now, remember the three-step guide to making model changes:
  240. * Change your models (in ``models.py``).
  241. * Run :djadmin:`python manage.py makemigrations <makemigrations>` to create
  242. migrations for those changes
  243. * Run :djadmin:`python manage.py migrate <migrate>` to apply those changes to
  244. the database.
  245. The reason that there are separate commands to make and apply migrations is
  246. because you'll commit migrations to your version control system and ship them
  247. with your app; they not only make your development easier, they're also
  248. usable by other developers and in production.
  249. Read the :doc:`django-admin documentation </ref/django-admin>` for full
  250. information on what the ``manage.py`` utility can do.
  251. Playing with the API
  252. ====================
  253. Now, let's hop into the interactive Python shell and play around with the free
  254. API Django gives you. To invoke the Python shell, use this command:
  255. .. console::
  256. $ python manage.py shell
  257. We're using this instead of simply typing "python", because :file:`manage.py`
  258. sets the :envvar:`DJANGO_SETTINGS_MODULE` environment variable, which gives
  259. Django the Python import path to your :file:`mysite/settings.py` file.
  260. Once you're in the shell, explore the :doc:`database API </topics/db/queries>`:
  261. .. code-block:: pycon
  262. >>> from polls.models import Choice, Question # Import the model classes we just wrote.
  263. # No questions are in the system yet.
  264. >>> Question.objects.all()
  265. <QuerySet []>
  266. # Create a new Question.
  267. # Support for time zones is enabled in the default settings file, so
  268. # Django expects a datetime with tzinfo for pub_date. Use timezone.now()
  269. # instead of datetime.datetime.now() and it will do the right thing.
  270. >>> from django.utils import timezone
  271. >>> q = Question(question_text="What's new?", pub_date=timezone.now())
  272. # Save the object into the database. You have to call save() explicitly.
  273. >>> q.save()
  274. # Now it has an ID.
  275. >>> q.id
  276. 1
  277. # Access model field values via Python attributes.
  278. >>> q.question_text
  279. "What's new?"
  280. >>> q.pub_date
  281. datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=datetime.timezone.utc)
  282. # Change values by changing the attributes, then calling save().
  283. >>> q.question_text = "What's up?"
  284. >>> q.save()
  285. # objects.all() displays all the questions in the database.
  286. >>> Question.objects.all()
  287. <QuerySet [<Question: Question object (1)>]>
  288. Wait a minute. ``<Question: Question object (1)>`` isn't a helpful
  289. representation of this object. Let's fix that by editing the ``Question`` model
  290. (in the ``polls/models.py`` file) and adding a
  291. :meth:`~django.db.models.Model.__str__` method to both ``Question`` and
  292. ``Choice``:
  293. .. code-block:: python
  294. :caption: ``polls/models.py``
  295. from django.db import models
  296. class Question(models.Model):
  297. # ...
  298. def __str__(self):
  299. return self.question_text
  300. class Choice(models.Model):
  301. # ...
  302. def __str__(self):
  303. return self.choice_text
  304. It's important to add :meth:`~django.db.models.Model.__str__` methods to your
  305. models, not only for your own convenience when dealing with the interactive
  306. prompt, but also because objects' representations are used throughout Django's
  307. automatically-generated admin.
  308. .. _tutorial02-import-timezone:
  309. Let's also add a custom method to this model:
  310. .. code-block:: python
  311. :caption: ``polls/models.py``
  312. import datetime
  313. from django.db import models
  314. from django.utils import timezone
  315. class Question(models.Model):
  316. # ...
  317. def was_published_recently(self):
  318. return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
  319. Note the addition of ``import datetime`` and ``from django.utils import
  320. timezone``, to reference Python's standard :mod:`datetime` module and Django's
  321. time-zone-related utilities in :mod:`django.utils.timezone`, respectively. If
  322. you aren't familiar with time zone handling in Python, you can learn more in
  323. the :doc:`time zone support docs </topics/i18n/timezones>`.
  324. Save these changes and start a new Python interactive shell by running
  325. ``python manage.py shell`` again:
  326. .. code-block:: pycon
  327. >>> from polls.models import Choice, Question
  328. # Make sure our __str__() addition worked.
  329. >>> Question.objects.all()
  330. <QuerySet [<Question: What's up?>]>
  331. # Django provides a rich database lookup API that's entirely driven by
  332. # keyword arguments.
  333. >>> Question.objects.filter(id=1)
  334. <QuerySet [<Question: What's up?>]>
  335. >>> Question.objects.filter(question_text__startswith="What")
  336. <QuerySet [<Question: What's up?>]>
  337. # Get the question that was published this year.
  338. >>> from django.utils import timezone
  339. >>> current_year = timezone.now().year
  340. >>> Question.objects.get(pub_date__year=current_year)
  341. <Question: What's up?>
  342. # Request an ID that doesn't exist, this will raise an exception.
  343. >>> Question.objects.get(id=2)
  344. Traceback (most recent call last):
  345. ...
  346. DoesNotExist: Question matching query does not exist.
  347. # Lookup by a primary key is the most common case, so Django provides a
  348. # shortcut for primary-key exact lookups.
  349. # The following is identical to Question.objects.get(id=1).
  350. >>> Question.objects.get(pk=1)
  351. <Question: What's up?>
  352. # Make sure our custom method worked.
  353. >>> q = Question.objects.get(pk=1)
  354. >>> q.was_published_recently()
  355. True
  356. # Give the Question a couple of Choices. The create call constructs a new
  357. # Choice object, does the INSERT statement, adds the choice to the set
  358. # of available choices and returns the new Choice object. Django creates
  359. # a set (defined as "choice_set") to hold the "other side" of a ForeignKey
  360. # relation (e.g. a question's choice) which can be accessed via the API.
  361. >>> q = Question.objects.get(pk=1)
  362. # Display any choices from the related object set -- none so far.
  363. >>> q.choice_set.all()
  364. <QuerySet []>
  365. # Create three choices.
  366. >>> q.choice_set.create(choice_text="Not much", votes=0)
  367. <Choice: Not much>
  368. >>> q.choice_set.create(choice_text="The sky", votes=0)
  369. <Choice: The sky>
  370. >>> c = q.choice_set.create(choice_text="Just hacking again", votes=0)
  371. # Choice objects have API access to their related Question objects.
  372. >>> c.question
  373. <Question: What's up?>
  374. # And vice versa: Question objects get access to Choice objects.
  375. >>> q.choice_set.all()
  376. <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
  377. >>> q.choice_set.count()
  378. 3
  379. # The API automatically follows relationships as far as you need.
  380. # Use double underscores to separate relationships.
  381. # This works as many levels deep as you want; there's no limit.
  382. # Find all Choices for any question whose pub_date is in this year
  383. # (reusing the 'current_year' variable we created above).
  384. >>> Choice.objects.filter(question__pub_date__year=current_year)
  385. <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
  386. # Let's delete one of the choices. Use delete() for that.
  387. >>> c = q.choice_set.filter(choice_text__startswith="Just hacking")
  388. >>> c.delete()
  389. For more information on model relations, see :doc:`Accessing related objects
  390. </ref/models/relations>`. For more on how to use double underscores to perform
  391. field lookups via the API, see :ref:`Field lookups <field-lookups-intro>`. For
  392. full details on the database API, see our :doc:`Database API reference
  393. </topics/db/queries>`.
  394. Introducing the Django Admin
  395. ============================
  396. .. admonition:: Philosophy
  397. Generating admin sites for your staff or clients to add, change, and delete
  398. content is tedious work that doesn't require much creativity. For that
  399. reason, Django entirely automates creation of admin interfaces for models.
  400. Django was written in a newsroom environment, with a very clear separation
  401. between "content publishers" and the "public" site. Site managers use the
  402. system to add news stories, events, sports scores, etc., and that content is
  403. displayed on the public site. Django solves the problem of creating a
  404. unified interface for site administrators to edit content.
  405. The admin isn't intended to be used by site visitors. It's for site
  406. managers.
  407. Creating an admin user
  408. ----------------------
  409. First we'll need to create a user who can login to the admin site. Run the
  410. following command:
  411. .. console::
  412. $ python manage.py createsuperuser
  413. Enter your desired username and press enter.
  414. .. code-block:: text
  415. Username: admin
  416. You will then be prompted for your desired email address:
  417. .. code-block:: text
  418. Email address: admin@example.com
  419. The final step is to enter your password. You will be asked to enter your
  420. password twice, the second time as a confirmation of the first.
  421. .. code-block:: text
  422. Password: **********
  423. Password (again): *********
  424. Superuser created successfully.
  425. Start the development server
  426. ----------------------------
  427. The Django admin site is activated by default. Let's start the development
  428. server and explore it.
  429. If the server is not running start it like so:
  430. .. console::
  431. $ python manage.py runserver
  432. Now, open a web browser and go to "/admin/" on your local domain -- e.g.,
  433. http://127.0.0.1:8000/admin/. You should see the admin's login screen:
  434. .. image:: _images/admin01.png
  435. :alt: Django admin login screen
  436. Since :doc:`translation </topics/i18n/translation>` is turned on by default, if
  437. you set :setting:`LANGUAGE_CODE`, the login screen will be displayed in the
  438. given language (if Django has appropriate translations).
  439. Enter the admin site
  440. --------------------
  441. Now, try logging in with the superuser account you created in the previous step.
  442. You should see the Django admin index page:
  443. .. image:: _images/admin02.png
  444. :alt: Django admin index page
  445. You should see a few types of editable content: groups and users. They are
  446. provided by :mod:`django.contrib.auth`, the authentication framework shipped
  447. by Django.
  448. Make the poll app modifiable in the admin
  449. -----------------------------------------
  450. But where's our poll app? It's not displayed on the admin index page.
  451. Only one more thing to do: we need to tell the admin that ``Question`` objects
  452. have an admin interface. To do this, open the :file:`polls/admin.py` file, and
  453. edit it to look like this:
  454. .. code-block:: python
  455. :caption: ``polls/admin.py``
  456. from django.contrib import admin
  457. from .models import Question
  458. admin.site.register(Question)
  459. Explore the free admin functionality
  460. ------------------------------------
  461. Now that we've registered ``Question``, Django knows that it should be displayed on
  462. the admin index page:
  463. .. image:: _images/admin03t.png
  464. :alt: Django admin index page, now with polls displayed
  465. Click "Questions". Now you're at the "change list" page for questions. This page
  466. displays all the questions in the database and lets you choose one to change it.
  467. There's the "What's up?" question we created earlier:
  468. .. image:: _images/admin04t.png
  469. :alt: Polls change list page
  470. Click the "What's up?" question to edit it:
  471. .. image:: _images/admin05t.png
  472. :alt: Editing form for question object
  473. Things to note here:
  474. * The form is automatically generated from the ``Question`` model.
  475. * The different model field types (:class:`~django.db.models.DateTimeField`,
  476. :class:`~django.db.models.CharField`) correspond to the appropriate HTML
  477. input widget. Each type of field knows how to display itself in the Django
  478. admin.
  479. * Each :class:`~django.db.models.DateTimeField` gets free JavaScript
  480. shortcuts. Dates get a "Today" shortcut and calendar popup, and times get
  481. a "Now" shortcut and a convenient popup that lists commonly entered times.
  482. The bottom part of the page gives you a couple of options:
  483. * Save -- Saves changes and returns to the change-list page for this type of
  484. object.
  485. * Save and continue editing -- Saves changes and reloads the admin page for
  486. this object.
  487. * Save and add another -- Saves changes and loads a new, blank form for this
  488. type of object.
  489. * Delete -- Displays a delete confirmation page.
  490. If the value of "Date published" doesn't match the time when you created the
  491. question in :doc:`Tutorial 1</intro/tutorial01>`, it probably
  492. means you forgot to set the correct value for the :setting:`TIME_ZONE` setting.
  493. Change it, reload the page and check that the correct value appears.
  494. Change the "Date published" by clicking the "Today" and "Now" shortcuts. Then
  495. click "Save and continue editing." Then click "History" in the upper right.
  496. You'll see a page listing all changes made to this object via the Django admin,
  497. with the timestamp and username of the person who made the change:
  498. .. image:: _images/admin06t.png
  499. :alt: History page for question object
  500. When you're comfortable with the models API and have familiarized yourself with
  501. the admin site, read :doc:`part 3 of this tutorial</intro/tutorial03>` to learn
  502. about how to add more views to our polls app.