tutorial02.txt 27 KB

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