tutorial02.txt 29 KB

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