tutorial02.txt 29 KB

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