tutorial02.txt 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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 setup the database, create your first model, and get a quick introduction
  6. to Django's automatically-generated admin site.
  7. Database setup
  8. ==============
  9. Now, open up :file:`mysite/settings.py`. It's a normal Python module with
  10. module-level variables representing Django settings.
  11. By default, the configuration uses SQLite. If you're new to databases, or
  12. you're just interested in trying Django, this is the easiest choice. SQLite is
  13. included in Python, so you won't need to install anything else to support your
  14. database. When starting your first real project, however, you may want to use a
  15. more scalable database like PostgreSQL, to avoid database-switching headaches
  16. down the road.
  17. If you wish to use another database, install the appropriate :ref:`database
  18. bindings <database-installation>` and change the following keys in the
  19. :setting:`DATABASES` ``'default'`` item to match your database connection
  20. settings:
  21. * :setting:`ENGINE <DATABASE-ENGINE>` -- Either
  22. ``'django.db.backends.sqlite3'``,
  23. ``'django.db.backends.postgresql'``,
  24. ``'django.db.backends.mysql'``, or
  25. ``'django.db.backends.oracle'``. Other backends are :ref:`also available
  26. <third-party-notes>`.
  27. * :setting:`NAME` -- The name of your database. If you're using SQLite, the
  28. database will be a file on your computer; in that case, :setting:`NAME`
  29. should be the full absolute path, including filename, of that file. The
  30. default value, ``BASE_DIR / 'db.sqlite3'``, will store the file in your
  31. project directory.
  32. If you are not using SQLite as your database, additional settings such as
  33. :setting:`USER`, :setting:`PASSWORD`, and :setting:`HOST` must be added.
  34. For more details, see the reference documentation for :setting:`DATABASES`.
  35. .. admonition:: For databases other than SQLite
  36. If you're using a database besides SQLite, make sure you've created a
  37. database by this point. Do that with "``CREATE DATABASE database_name;``"
  38. within your database's interactive prompt.
  39. Also make sure that the database user provided in :file:`mysite/settings.py`
  40. has "create database" privileges. This allows automatic creation of a
  41. :ref:`test database <the-test-database>` which will be needed in a later
  42. tutorial.
  43. If you're using SQLite, you don't need to create anything beforehand - the
  44. database file will be created automatically when it is needed.
  45. While you're editing :file:`mysite/settings.py`, set :setting:`TIME_ZONE` to
  46. your time zone.
  47. Also, note the :setting:`INSTALLED_APPS` setting at the top of the file. That
  48. holds the names of all Django applications that are activated in this Django
  49. instance. Apps can be used in multiple projects, and you can package and
  50. distribute them for use by others in their projects.
  51. By default, :setting:`INSTALLED_APPS` contains the following apps, all of which
  52. come with Django:
  53. * :mod:`django.contrib.admin` -- The admin site. You'll use it shortly.
  54. * :mod:`django.contrib.auth` -- An authentication system.
  55. * :mod:`django.contrib.contenttypes` -- A framework for content types.
  56. * :mod:`django.contrib.sessions` -- A session framework.
  57. * :mod:`django.contrib.messages` -- A messaging framework.
  58. * :mod:`django.contrib.staticfiles` -- A framework for managing
  59. static files.
  60. These applications are included by default as a convenience for the common case.
  61. Some of these applications make use of at least one database table, though,
  62. so we need to create the tables in the database before we can use them. To do
  63. that, run the following command:
  64. .. console::
  65. $ python manage.py migrate
  66. The :djadmin:`migrate` command looks at the :setting:`INSTALLED_APPS` setting
  67. and creates any necessary database tables according to the database settings
  68. in your :file:`mysite/settings.py` file and the database migrations shipped
  69. with the app (we'll cover those later). You'll see a message for each
  70. migration it applies. If you're interested, run the command-line client for your
  71. database and type ``\dt`` (PostgreSQL), ``SHOW TABLES;`` (MariaDB, MySQL),
  72. ``.schema`` (SQLite), or ``SELECT TABLE_NAME FROM USER_TABLES;`` (Oracle) to
  73. display the tables Django created.
  74. .. admonition:: For the minimalists
  75. Like we said above, the default applications are included for the common
  76. case, but not everybody needs them. If you don't need any or all of them,
  77. feel free to comment-out or delete the appropriate line(s) from
  78. :setting:`INSTALLED_APPS` before running :djadmin:`migrate`. The
  79. :djadmin:`migrate` command will only run migrations for apps in
  80. :setting:`INSTALLED_APPS`.
  81. .. _creating-models:
  82. Creating models
  83. ===============
  84. Now we'll define your models -- essentially, your database layout, with
  85. additional metadata.
  86. .. admonition:: Philosophy
  87. A model is the single, definitive source of truth about your data. It contains
  88. the essential fields and behaviors of the data you're storing. Django follows
  89. the :ref:`DRY Principle <dry>`. The goal is to define your data model in one
  90. place and automatically derive things from it.
  91. This includes the migrations - unlike in Ruby On Rails, for example, migrations
  92. are entirely derived from your models file, and are essentially a
  93. history that Django can roll through to update your database schema to
  94. match your current models.
  95. In our poll app, we'll create two models: ``Question`` and ``Choice``. A
  96. ``Question`` has a question and a publication date. A ``Choice`` has two
  97. fields: the text of the choice and a vote tally. Each ``Choice`` is associated
  98. with a ``Question``.
  99. These concepts are represented by Python classes. Edit the
  100. :file:`polls/models.py` file so it looks like this:
  101. .. code-block:: python
  102. :caption: polls/models.py
  103. from django.db import models
  104. class Question(models.Model):
  105. question_text = models.CharField(max_length=200)
  106. pub_date = models.DateTimeField('date published')
  107. class Choice(models.Model):
  108. question = models.ForeignKey(Question, on_delete=models.CASCADE)
  109. choice_text = models.CharField(max_length=200)
  110. votes = models.IntegerField(default=0)
  111. Here, each model is represented by a class that subclasses
  112. :class:`django.db.models.Model`. Each model has a number of class variables,
  113. each of which represents a database field in the model.
  114. Each field is represented by an instance of a :class:`~django.db.models.Field`
  115. class -- e.g., :class:`~django.db.models.CharField` for character fields and
  116. :class:`~django.db.models.DateTimeField` for datetimes. This tells Django what
  117. type of data each field holds.
  118. The name of each :class:`~django.db.models.Field` instance (e.g.
  119. ``question_text`` or ``pub_date``) is the field's name, in machine-friendly
  120. format. You'll use this value in your Python code, and your database will use
  121. it as the column name.
  122. You can use an optional first positional argument to a
  123. :class:`~django.db.models.Field` to designate a human-readable name. That's used
  124. in a couple of introspective parts of Django, and it doubles as documentation.
  125. If this field isn't provided, Django will use the machine-readable name. In this
  126. example, we've only defined a human-readable name for ``Question.pub_date``.
  127. For all other fields in this model, the field's machine-readable name will
  128. suffice as its human-readable name.
  129. Some :class:`~django.db.models.Field` classes have required arguments.
  130. :class:`~django.db.models.CharField`, for example, requires that you give it a
  131. :attr:`~django.db.models.CharField.max_length`. That's used not only in the
  132. database schema, but in validation, as we'll soon see.
  133. A :class:`~django.db.models.Field` can also have various optional arguments; in
  134. this case, we've set the :attr:`~django.db.models.Field.default` value of
  135. ``votes`` to 0.
  136. Finally, note a relationship is defined, using
  137. :class:`~django.db.models.ForeignKey`. That tells Django each ``Choice`` is
  138. related to a single ``Question``. Django supports all the common database
  139. relationships: many-to-one, many-to-many, and one-to-one.
  140. Activating models
  141. =================
  142. That small bit of model code gives Django a lot of information. With it, Django
  143. is able to:
  144. * Create a database schema (``CREATE TABLE`` statements) for this app.
  145. * Create a Python database-access API for accessing ``Question`` and ``Choice`` objects.
  146. But first we need to tell our project that the ``polls`` app is installed.
  147. .. admonition:: Philosophy
  148. Django apps are "pluggable": You can use an app in multiple projects, and
  149. you can distribute apps, because they don't have to be tied to a given
  150. Django installation.
  151. To include the app in our project, we need to add a reference to its
  152. configuration class in the :setting:`INSTALLED_APPS` setting. The
  153. ``PollsConfig`` class is in the :file:`polls/apps.py` file, so its dotted path
  154. is ``'polls.apps.PollsConfig'``. Edit the :file:`mysite/settings.py` file and
  155. add that dotted path to the :setting:`INSTALLED_APPS` setting. It'll look like
  156. this:
  157. .. code-block:: python
  158. :caption: mysite/settings.py
  159. INSTALLED_APPS = [
  160. 'polls.apps.PollsConfig',
  161. 'django.contrib.admin',
  162. 'django.contrib.auth',
  163. 'django.contrib.contenttypes',
  164. 'django.contrib.sessions',
  165. 'django.contrib.messages',
  166. 'django.contrib.staticfiles',
  167. ]
  168. Now Django knows to include the ``polls`` app. Let's run another command:
  169. .. console::
  170. $ python manage.py makemigrations polls
  171. You should see something similar to the following:
  172. .. code-block:: text
  173. Migrations for 'polls':
  174. polls/migrations/0001_initial.py:
  175. - Create model Choice
  176. - Create model Question
  177. - Add field question to choice
  178. By running ``makemigrations``, you're telling Django that you've made
  179. some changes to your models (in this case, you've made new ones) and that
  180. you'd like the changes to be stored as a *migration*.
  181. Migrations are how Django stores changes to your models (and thus your
  182. database schema) - they're files on disk. You can read the migration for your
  183. new model if you like; it's the file ``polls/migrations/0001_initial.py``.
  184. Don't worry, you're not expected to read them every time Django makes one, but
  185. they're designed to be human-editable in case you want to manually tweak how
  186. Django changes things.
  187. There's a command that will run the migrations for you and manage your database
  188. schema automatically - that's called :djadmin:`migrate`, and we'll come to it in a
  189. moment - but first, let's see what SQL that migration would run. The
  190. :djadmin:`sqlmigrate` command takes migration names and returns their SQL:
  191. .. console::
  192. $ python manage.py sqlmigrate polls 0001
  193. You should see something similar to the following (we've reformatted it for
  194. readability):
  195. .. code-block:: sql
  196. BEGIN;
  197. --
  198. -- Create model Choice
  199. --
  200. CREATE TABLE "polls_choice" (
  201. "id" serial NOT NULL PRIMARY KEY,
  202. "choice_text" varchar(200) NOT NULL,
  203. "votes" integer NOT NULL
  204. );
  205. --
  206. -- Create model Question
  207. --
  208. CREATE TABLE "polls_question" (
  209. "id" serial NOT NULL PRIMARY KEY,
  210. "question_text" varchar(200) NOT NULL,
  211. "pub_date" timestamp with time zone NOT NULL
  212. );
  213. --
  214. -- Add field question to choice
  215. --
  216. ALTER TABLE "polls_choice" ADD COLUMN "question_id" integer NOT NULL;
  217. ALTER TABLE "polls_choice" ALTER COLUMN "question_id" DROP DEFAULT;
  218. CREATE INDEX "polls_choice_7aa0f6ee" ON "polls_choice" ("question_id");
  219. ALTER TABLE "polls_choice"
  220. ADD CONSTRAINT "polls_choice_question_id_246c99a640fbbd72_fk_polls_question_id"
  221. FOREIGN KEY ("question_id")
  222. REFERENCES "polls_question" ("id")
  223. DEFERRABLE INITIALLY DEFERRED;
  224. COMMIT;
  225. Note the following:
  226. * The exact output will vary depending on the database you are using. The
  227. example above is generated for PostgreSQL.
  228. * Table names are automatically generated by combining the name of the app
  229. (``polls``) and the lowercase name of the model -- ``question`` and
  230. ``choice``. (You can override this behavior.)
  231. * Primary keys (IDs) are added automatically. (You can override this, too.)
  232. * By convention, Django appends ``"_id"`` to the foreign key field name.
  233. (Yes, you can override this, as well.)
  234. * The foreign key relationship is made explicit by a ``FOREIGN KEY``
  235. constraint. Don't worry about the ``DEFERRABLE`` parts; it's telling
  236. PostgreSQL to not enforce the foreign key until the end of the transaction.
  237. * It's tailored to the database you're using, so database-specific field types
  238. such as ``auto_increment`` (MySQL), ``serial`` (PostgreSQL), or ``integer
  239. primary key autoincrement`` (SQLite) are handled for you automatically. Same
  240. goes for the quoting of field names -- e.g., using double quotes or
  241. single quotes.
  242. * The :djadmin:`sqlmigrate` command doesn't actually run the migration on your
  243. database - instead, it prints it to the screen so that you can see what SQL
  244. Django thinks is required. It's useful for checking what Django is going to
  245. do or if you have database administrators who require SQL scripts for
  246. changes.
  247. If you're interested, you can also run
  248. :djadmin:`python manage.py check <check>`; this checks for any problems in
  249. your project without making migrations or touching the database.
  250. Now, run :djadmin:`migrate` again to create those model tables in your database:
  251. .. console::
  252. $ python manage.py migrate
  253. Operations to perform:
  254. Apply all migrations: admin, auth, contenttypes, polls, sessions
  255. Running migrations:
  256. Rendering model states... DONE
  257. Applying polls.0001_initial... OK
  258. The :djadmin:`migrate` command takes all the migrations that haven't been
  259. applied (Django tracks which ones are applied using a special table in your
  260. database called ``django_migrations``) and runs them against your database -
  261. essentially, synchronizing the changes you made to your models with the schema
  262. in the database.
  263. Migrations are very powerful and let you change your models over time, as you
  264. develop your project, without the need to delete your database or tables and
  265. make new ones - it specializes in upgrading your database live, without
  266. losing data. We'll cover them in more depth in a later part of the tutorial,
  267. but for now, remember the three-step guide to making model changes:
  268. * Change your models (in ``models.py``).
  269. * Run :djadmin:`python manage.py makemigrations <makemigrations>` to create
  270. migrations for those changes
  271. * Run :djadmin:`python manage.py migrate <migrate>` to apply those changes to
  272. the database.
  273. The reason that there are separate commands to make and apply migrations is
  274. because you'll commit migrations to your version control system and ship them
  275. with your app; they not only make your development easier, they're also
  276. usable by other developers and in production.
  277. Read the :doc:`django-admin documentation </ref/django-admin>` for full
  278. information on what the ``manage.py`` utility can do.
  279. Playing with the API
  280. ====================
  281. Now, let's hop into the interactive Python shell and play around with the free
  282. API Django gives you. To invoke the Python shell, use this command:
  283. .. console::
  284. $ python manage.py shell
  285. We're using this instead of simply typing "python", because :file:`manage.py`
  286. sets the ``DJANGO_SETTINGS_MODULE`` environment variable, which gives Django
  287. the Python import path to your :file:`mysite/settings.py` file.
  288. Once you're in the shell, explore the :doc:`database API </topics/db/queries>`::
  289. >>> from polls.models import Choice, Question # Import the model classes we just wrote.
  290. # No questions are in the system yet.
  291. >>> Question.objects.all()
  292. <QuerySet []>
  293. # Create a new Question.
  294. # Support for time zones is enabled in the default settings file, so
  295. # Django expects a datetime with tzinfo for pub_date. Use timezone.now()
  296. # instead of datetime.datetime.now() and it will do the right thing.
  297. >>> from django.utils import timezone
  298. >>> q = Question(question_text="What's new?", pub_date=timezone.now())
  299. # Save the object into the database. You have to call save() explicitly.
  300. >>> q.save()
  301. # Now it has an ID.
  302. >>> q.id
  303. 1
  304. # Access model field values via Python attributes.
  305. >>> q.question_text
  306. "What's new?"
  307. >>> q.pub_date
  308. datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)
  309. # Change values by changing the attributes, then calling save().
  310. >>> q.question_text = "What's up?"
  311. >>> q.save()
  312. # objects.all() displays all the questions in the database.
  313. >>> Question.objects.all()
  314. <QuerySet [<Question: Question object (1)>]>
  315. Wait a minute. ``<Question: Question object (1)>`` isn't a helpful
  316. representation of this object. Let's fix that by editing the ``Question`` model
  317. (in the ``polls/models.py`` file) and adding a
  318. :meth:`~django.db.models.Model.__str__` method to both ``Question`` and
  319. ``Choice``:
  320. .. code-block:: python
  321. :caption: polls/models.py
  322. from django.db import models
  323. class Question(models.Model):
  324. # ...
  325. def __str__(self):
  326. return self.question_text
  327. class Choice(models.Model):
  328. # ...
  329. def __str__(self):
  330. return self.choice_text
  331. It's important to add :meth:`~django.db.models.Model.__str__` methods to your
  332. models, not only for your own convenience when dealing with the interactive
  333. prompt, but also because objects' representations are used throughout Django's
  334. automatically-generated admin.
  335. .. _tutorial02-import-timezone:
  336. Let's also add a custom method to this model:
  337. .. code-block:: python
  338. :caption: polls/models.py
  339. import datetime
  340. from django.db import models
  341. from django.utils import timezone
  342. class Question(models.Model):
  343. # ...
  344. def was_published_recently(self):
  345. return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
  346. Note the addition of ``import datetime`` and ``from django.utils import
  347. timezone``, to reference Python's standard :mod:`datetime` module and Django's
  348. time-zone-related utilities in :mod:`django.utils.timezone`, respectively. If
  349. you aren't familiar with time zone handling in Python, you can learn more in
  350. the :doc:`time zone support docs </topics/i18n/timezones>`.
  351. Save these changes and start a new Python interactive shell by running
  352. ``python manage.py shell`` again::
  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 to hold the "other side" of a ForeignKey relation
  386. # (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,
  463. the login screen may be displayed in your own language, depending on your
  464. browser's settings and if Django has a translation for this language.
  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.