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