tutorial02.txt 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. =====================================
  2. Writing your first Django app, part 2
  3. =====================================
  4. This tutorial begins where :doc:`Tutorial 1 </intro/tutorial01>` left off. We're
  5. continuing the Web-poll application and will focus on Django's
  6. automatically-generated admin site.
  7. .. admonition:: Philosophy
  8. Generating admin sites for your staff or clients to add, change and delete
  9. content is tedious work that doesn't require much creativity. For that
  10. reason, Django entirely automates creation of admin interfaces for models.
  11. Django was written in a newsroom environment, with a very clear separation
  12. between "content publishers" and the "public" site. Site managers use the
  13. system to add news stories, events, sports scores, etc., and that content is
  14. displayed on the public site. Django solves the problem of creating a
  15. unified interface for site administrators to edit content.
  16. The admin isn't intended to be used by site visitors. It's for site
  17. managers.
  18. Start the development server
  19. ============================
  20. The Django admin site is activated by default. Let's start the development
  21. server and explore it.
  22. Recall from Tutorial 1 that you start the development server like so:
  23. .. code-block:: bash
  24. python manage.py runserver
  25. Now, open a Web browser and go to "/admin/" on your local domain -- e.g.,
  26. http://127.0.0.1:8000/admin/. You should see the admin's login screen:
  27. .. image:: _images/admin01.png
  28. :alt: Django admin login screen
  29. Since :doc:`translation </topics/i18n/translation>` is turned on by default,
  30. the login screen may be displayed in your own language, depending on your
  31. browser's settings and on whether Django has a translation for this language.
  32. .. admonition:: Doesn't match what you see?
  33. If at this point, instead of the above login page, you get an error
  34. page reporting something like::
  35. ImportError at /admin/
  36. cannot import name patterns
  37. ...
  38. then you're probably using a version of Django that doesn't match this
  39. tutorial version. You'll want to either switch to the older tutorial or the
  40. newer Django version.
  41. Enter the admin site
  42. ====================
  43. Now, try logging in. You created a superuser account in the first part of this
  44. tutorial, remember? If you didn't create one or forgot the password you can
  45. :ref:`create another one <topics-auth-creating-superusers>`.
  46. You should see the Django admin index page:
  47. .. image:: _images/admin02t.png
  48. :alt: Django admin index page
  49. You should see a few types of editable content: groups and users. They are
  50. provided by :mod:`django.contrib.auth`, the authentication framework shipped
  51. by Django.
  52. Make the poll app modifiable in the admin
  53. =========================================
  54. But where's our poll app? It's not displayed on the admin index page.
  55. Just one thing to do: we need to tell the admin that ``Poll``
  56. objects have an admin interface. To do this, open the file called
  57. ``admin.py`` in your ``polls`` directory, and edit it to look like this::
  58. from django.contrib import admin
  59. from polls.models import Poll
  60. admin.site.register(Poll)
  61. Explore the free admin functionality
  62. ====================================
  63. Now that we've registered ``Poll``, Django knows that it should be displayed on
  64. the admin index page:
  65. .. image:: _images/admin03t.png
  66. :alt: Django admin index page, now with polls displayed
  67. Click "Polls." Now you're at the "change list" page for polls. This page
  68. displays all the polls in the database and lets you choose one to change it.
  69. There's the "What's up?" poll we created in the first tutorial:
  70. .. image:: _images/admin04t.png
  71. :alt: Polls change list page
  72. Click the "What's up?" poll to edit it:
  73. .. image:: _images/admin05t.png
  74. :alt: Editing form for poll object
  75. Things to note here:
  76. * The form is automatically generated from the ``Poll`` model.
  77. * The different model field types (:class:`~django.db.models.DateTimeField`,
  78. :class:`~django.db.models.CharField`) correspond to the appropriate HTML
  79. input widget. Each type of field knows how to display itself in the Django
  80. admin.
  81. * Each :class:`~django.db.models.DateTimeField` gets free JavaScript
  82. shortcuts. Dates get a "Today" shortcut and calendar popup, and times get
  83. a "Now" shortcut and a convenient popup that lists commonly entered times.
  84. The bottom part of the page gives you a couple of options:
  85. * Save -- Saves changes and returns to the change-list page for this type of
  86. object.
  87. * Save and continue editing -- Saves changes and reloads the admin page for
  88. this object.
  89. * Save and add another -- Saves changes and loads a new, blank form for this
  90. type of object.
  91. * Delete -- Displays a delete confirmation page.
  92. If the value of "Date published" doesn't match the time when you created the
  93. poll in Tutorial 1, it probably means you forgot to set the correct value for
  94. the :setting:`TIME_ZONE` setting. Change it, reload the page and check that
  95. the correct value appears.
  96. Change the "Date published" by clicking the "Today" and "Now" shortcuts. Then
  97. click "Save and continue editing." Then click "History" in the upper right.
  98. You'll see a page listing all changes made to this object via the Django admin,
  99. with the timestamp and username of the person who made the change:
  100. .. image:: _images/admin06t.png
  101. :alt: History page for poll object
  102. Customize the admin form
  103. ========================
  104. Take a few minutes to marvel at all the code you didn't have to write. By
  105. registering the Poll model with ``admin.site.register(Poll)``, Django was able
  106. to construct a default form representation. Often, you'll want to customize how
  107. the admin form looks and works. You'll do this by telling Django the options
  108. you want when you register the object.
  109. Let's see how this works by re-ordering the fields on the edit form. Replace
  110. the ``admin.site.register(Poll)`` line with::
  111. class PollAdmin(admin.ModelAdmin):
  112. fields = ['pub_date', 'question']
  113. admin.site.register(Poll, PollAdmin)
  114. You'll follow this pattern -- create a model admin object, then pass it as the
  115. second argument to ``admin.site.register()`` -- any time you need to change the
  116. admin options for an object.
  117. This particular change above makes the "Publication date" come before the
  118. "Question" field:
  119. .. image:: _images/admin07.png
  120. :alt: Fields have been reordered
  121. This isn't impressive with only two fields, but for admin forms with dozens
  122. of fields, choosing an intuitive order is an important usability detail.
  123. And speaking of forms with dozens of fields, you might want to split the form
  124. up into fieldsets::
  125. class PollAdmin(admin.ModelAdmin):
  126. fieldsets = [
  127. (None, {'fields': ['question']}),
  128. ('Date information', {'fields': ['pub_date']}),
  129. ]
  130. admin.site.register(Poll, PollAdmin)
  131. The first element of each tuple in ``fieldsets`` is the title of the fieldset.
  132. Here's what our form looks like now:
  133. .. image:: _images/admin08t.png
  134. :alt: Form has fieldsets now
  135. You can assign arbitrary HTML classes to each fieldset. Django provides a
  136. ``"collapse"`` class that displays a particular fieldset initially collapsed.
  137. This is useful when you have a long form that contains a number of fields that
  138. aren't commonly used::
  139. class PollAdmin(admin.ModelAdmin):
  140. fieldsets = [
  141. (None, {'fields': ['question']}),
  142. ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
  143. ]
  144. .. image:: _images/admin09.png
  145. :alt: Fieldset is initially collapsed
  146. Adding related objects
  147. ======================
  148. OK, we have our Poll admin page. But a ``Poll`` has multiple ``Choices``, and
  149. the admin page doesn't display choices.
  150. Yet.
  151. There are two ways to solve this problem. The first is to register ``Choice``
  152. with the admin just as we did with ``Poll``. That's easy::
  153. from polls.models import Choice
  154. admin.site.register(Choice)
  155. Now "Choices" is an available option in the Django admin. The "Add choice" form
  156. looks like this:
  157. .. image:: _images/admin10.png
  158. :alt: Choice admin page
  159. In that form, the "Poll" field is a select box containing every poll in the
  160. database. Django knows that a :class:`~django.db.models.ForeignKey` should be
  161. represented in the admin as a ``<select>`` box. In our case, only one poll
  162. exists at this point.
  163. Also note the "Add Another" link next to "Poll." Every object with a
  164. ``ForeignKey`` relationship to another gets this for free. When you click "Add
  165. Another," you'll get a popup window with the "Add poll" form. If you add a poll
  166. in that window and click "Save," Django will save the poll to the database and
  167. dynamically add it as the selected choice on the "Add choice" form you're
  168. looking at.
  169. But, really, this is an inefficient way of adding ``Choice`` objects to the system.
  170. It'd be better if you could add a bunch of Choices directly when you create the
  171. ``Poll`` object. Let's make that happen.
  172. Remove the ``register()`` call for the ``Choice`` model. Then, edit the ``Poll``
  173. registration code to read::
  174. from django.contrib import admin
  175. from polls.models import Choice, Poll
  176. class ChoiceInline(admin.StackedInline):
  177. model = Choice
  178. extra = 3
  179. class PollAdmin(admin.ModelAdmin):
  180. fieldsets = [
  181. (None, {'fields': ['question']}),
  182. ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
  183. ]
  184. inlines = [ChoiceInline]
  185. admin.site.register(Poll, PollAdmin)
  186. This tells Django: "``Choice`` objects are edited on the ``Poll`` admin page. By
  187. default, provide enough fields for 3 choices."
  188. Load the "Add poll" page to see how that looks:
  189. .. image:: _images/admin11t.png
  190. :alt: Add poll page now has choices on it
  191. It works like this: There are three slots for related Choices -- as specified
  192. by ``extra`` -- and each time you come back to the "Change" page for an
  193. already-created object, you get another three extra slots.
  194. At the end of the three current slots you will find an "Add another Choice"
  195. link. If you click on it, a new slot will be added. If you want to remove the
  196. added slot, you can click on the X to the top right of the added slot. Note
  197. that you can't remove the original three slots. This image shows an added slot:
  198. .. image:: _images/admin15t.png
  199. :alt: Additional slot added dynamically
  200. One small problem, though. It takes a lot of screen space to display all the
  201. fields for entering related ``Choice`` objects. For that reason, Django offers a
  202. tabular way of displaying inline related objects; you just need to change
  203. the ``ChoiceInline`` declaration to read::
  204. class ChoiceInline(admin.TabularInline):
  205. #...
  206. With that ``TabularInline`` (instead of ``StackedInline``), the
  207. related objects are displayed in a more compact, table-based format:
  208. .. image:: _images/admin12t.png
  209. :alt: Add poll page now has more compact choices
  210. Note that there is an extra "Delete?" column that allows removing rows added
  211. using the "Add Another Choice" button and rows that have already been saved.
  212. Customize the admin change list
  213. ===============================
  214. Now that the Poll admin page is looking good, let's make some tweaks to the
  215. "change list" page -- the one that displays all the polls in the system.
  216. Here's what it looks like at this point:
  217. .. image:: _images/admin04t.png
  218. :alt: Polls change list page
  219. By default, Django displays the ``str()`` of each object. But sometimes it'd be
  220. more helpful if we could display individual fields. To do that, use the
  221. ``list_display`` admin option, which is a tuple of field names to display, as
  222. columns, on the change list page for the object::
  223. class PollAdmin(admin.ModelAdmin):
  224. # ...
  225. list_display = ('question', 'pub_date')
  226. Just for good measure, let's also include the ``was_published_recently`` custom
  227. method from Tutorial 1::
  228. class PollAdmin(admin.ModelAdmin):
  229. # ...
  230. list_display = ('question', 'pub_date', 'was_published_recently')
  231. Now the poll change list page looks like this:
  232. .. image:: _images/admin13t.png
  233. :alt: Polls change list page, updated
  234. You can click on the column headers to sort by those values -- except in the
  235. case of the ``was_published_recently`` header, because sorting by the output
  236. of an arbitrary method is not supported. Also note that the column header for
  237. ``was_published_recently`` is, by default, the name of the method (with
  238. underscores replaced with spaces), and that each line contains the string
  239. representation of the output.
  240. You can improve that by giving that method (in ``models.py``) a few
  241. attributes, as follows::
  242. class Poll(models.Model):
  243. # ...
  244. def was_published_recently(self):
  245. return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
  246. was_published_recently.admin_order_field = 'pub_date'
  247. was_published_recently.boolean = True
  248. was_published_recently.short_description = 'Published recently?'
  249. Edit your admin.py file again and add an improvement to the Poll change list page: Filters. Add the
  250. following line to ``PollAdmin``::
  251. list_filter = ['pub_date']
  252. That adds a "Filter" sidebar that lets people filter the change list by the
  253. ``pub_date`` field:
  254. .. image:: _images/admin14t.png
  255. :alt: Polls change list page, updated
  256. The type of filter displayed depends on the type of field you're filtering on.
  257. Because ``pub_date`` is a :class:`~django.db.models.DateTimeField`, Django
  258. knows to give appropriate filter options: "Any date," "Today," "Past 7 days,"
  259. "This month," "This year."
  260. This is shaping up well. Let's add some search capability::
  261. search_fields = ['question']
  262. That adds a search box at the top of the change list. When somebody enters
  263. search terms, Django will search the ``question`` field. You can use as many
  264. fields as you'd like -- although because it uses a ``LIKE`` query behind the
  265. scenes, keep it reasonable, to keep your database happy.
  266. Finally, because ``Poll`` objects have dates, it'd be convenient to be able to
  267. drill down by date. Add this line::
  268. date_hierarchy = 'pub_date'
  269. That adds hierarchical navigation, by date, to the top of the change list page.
  270. At top level, it displays all available years. Then it drills down to months
  271. and, ultimately, days.
  272. Now's also a good time to note that change lists give you free pagination. The
  273. default is to display 100 items per page. Change-list pagination, search boxes,
  274. filters, date-hierarchies and column-header-ordering all work together like you
  275. think they should.
  276. Customize the admin look and feel
  277. =================================
  278. Clearly, having "Django administration" at the top of each admin page is
  279. ridiculous. It's just placeholder text.
  280. That's easy to change, though, using Django's template system. The Django admin
  281. is powered by Django itself, and its interfaces use Django's own template
  282. system.
  283. Create a ``mytemplates`` directory in your project directory. Templates can
  284. live anywhere on your filesystem that Django can access. (Django runs as
  285. whatever user your server runs.) However, keeping your templates within the
  286. project is a good convention to follow.
  287. Open your settings file (``mysite/settings.py``, remember) and add a
  288. :setting:`TEMPLATE_DIRS` setting::
  289. TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'mytemplates'),)
  290. Don't forget the trailing comma. :setting:`TEMPLATE_DIRS` is a tuple of
  291. filesystem directories to check when loading Django templates; it's a search
  292. path.
  293. Now create a directory called ``admin`` inside ``mytemplates``, and copy the
  294. template ``admin/base_site.html`` from within the default Django admin
  295. template directory in the source code of Django itself
  296. (``django/contrib/admin/templates``) into that directory.
  297. .. admonition:: Where are the Django source files?
  298. If you have difficulty finding where the Django source files are located
  299. on your system, run the following command:
  300. .. code-block:: bash
  301. python -c "
  302. import sys
  303. sys.path = sys.path[1:]
  304. import django
  305. print(django.__path__)"
  306. Then, just edit the file and replace the generic Django text with your own
  307. site's name as you see fit.
  308. This template file contains lots of text like ``{% block branding %}``
  309. and ``{{ title }}``. The ``{%`` and ``{{`` tags are part of Django's
  310. template language. When Django renders ``admin/base_site.html``, this
  311. template language will be evaluated to produce the final HTML page.
  312. Don't worry if you can't make any sense of the template right now --
  313. we'll delve into Django's templating language in Tutorial 3.
  314. Note that any of Django's default admin templates can be overridden. To
  315. override a template, just do the same thing you did with ``base_site.html`` --
  316. copy it from the default directory into your custom directory, and make
  317. changes.
  318. Astute readers will ask: But if :setting:`TEMPLATE_DIRS` was empty by default,
  319. how was Django finding the default admin templates? The answer is that, by
  320. default, Django automatically looks for a ``templates/`` subdirectory within
  321. each app package, for use as a fallback. See the :ref:`template loader
  322. documentation <template-loaders>` for full information.
  323. Customize the admin index page
  324. ==============================
  325. On a similar note, you might want to customize the look and feel of the Django
  326. admin index page.
  327. By default, it displays all the apps in :setting:`INSTALLED_APPS` that have been
  328. registered with the admin application, in alphabetical order. You may want to
  329. make significant changes to the layout. After all, the index is probably the
  330. most important page of the admin, and it should be easy to use.
  331. The template to customize is ``admin/index.html``. (Do the same as with
  332. ``admin/base_site.html`` in the previous section -- copy it from the default
  333. directory to your custom template directory.) Edit the file, and you'll see it
  334. uses a template variable called ``app_list``. That variable contains every
  335. installed Django app. Instead of using that, you can hard-code links to
  336. object-specific admin pages in whatever way you think is best. Again,
  337. don't worry if you can't understand the template language -- we'll cover that
  338. in more detail in Tutorial 3.
  339. When you're comfortable with the admin site, read :doc:`part 3 of this tutorial
  340. </intro/tutorial03>` to start working on public poll views.