tutorial02.txt 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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/admin02.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 ``Question``
  56. objects have an admin interface. To do this, open the :file:`polls/admin.py`
  57. file, and edit it to look like this:
  58. .. snippet::
  59. :filename: polls/admin.py
  60. from django.contrib import admin
  61. from polls.models import Question
  62. admin.site.register(Question)
  63. Explore the free admin functionality
  64. ====================================
  65. Now that we've registered ``Question``, Django knows that it should be displayed on
  66. the admin index page:
  67. .. image:: _images/admin03t.png
  68. :alt: Django admin index page, now with polls displayed
  69. Click "Questions". Now you're at the "change list" page for questions. This page
  70. displays all the question in the database and lets you choose one to change it.
  71. There's the "What's up?" question we created in the first tutorial:
  72. .. image:: _images/admin04t.png
  73. :alt: Polls change list page
  74. Click the "What's up?" question to edit it:
  75. .. image:: _images/admin05t.png
  76. :alt: Editing form for question object
  77. Things to note here:
  78. * The form is automatically generated from the ``Question`` model.
  79. * The different model field types (:class:`~django.db.models.DateTimeField`,
  80. :class:`~django.db.models.CharField`) correspond to the appropriate HTML
  81. input widget. Each type of field knows how to display itself in the Django
  82. admin.
  83. * Each :class:`~django.db.models.DateTimeField` gets free JavaScript
  84. shortcuts. Dates get a "Today" shortcut and calendar popup, and times get
  85. a "Now" shortcut and a convenient popup that lists commonly entered times.
  86. The bottom part of the page gives you a couple of options:
  87. * Save -- Saves changes and returns to the change-list page for this type of
  88. object.
  89. * Save and continue editing -- Saves changes and reloads the admin page for
  90. this object.
  91. * Save and add another -- Saves changes and loads a new, blank form for this
  92. type of object.
  93. * Delete -- Displays a delete confirmation page.
  94. If the value of "Date published" doesn't match the time when you created the
  95. question in Tutorial 1, it probably means you forgot to set the correct value for
  96. the :setting:`TIME_ZONE` setting. Change it, reload the page and check that
  97. the correct value appears.
  98. Change the "Date published" by clicking the "Today" and "Now" shortcuts. Then
  99. click "Save and continue editing." Then click "History" in the upper right.
  100. You'll see a page listing all changes made to this object via the Django admin,
  101. with the timestamp and username of the person who made the change:
  102. .. image:: _images/admin06t.png
  103. :alt: History page for question object
  104. Customize the admin form
  105. ========================
  106. Take a few minutes to marvel at all the code you didn't have to write. By
  107. registering the ``Question`` model with ``admin.site.register(Question)``,
  108. Django was able to construct a default form representation. Often, you'll want
  109. to customize how the admin form looks and works. You'll do this by telling
  110. Django the options you want when you register the object.
  111. Let's see how this works by re-ordering the fields on the edit form. Replace
  112. the ``admin.site.register(Question)`` line with:
  113. .. snippet::
  114. :filename: polls/admin.py
  115. from django.contrib import admin
  116. from polls.models import Question
  117. class QuestionAdmin(admin.ModelAdmin):
  118. fields = ['pub_date', 'question_text']
  119. admin.site.register(Question, QuestionAdmin)
  120. You'll follow this pattern -- create a model admin object, then pass it as the
  121. second argument to ``admin.site.register()`` -- any time you need to change the
  122. admin options for an object.
  123. This particular change above makes the "Publication date" come before the
  124. "Question" field:
  125. .. image:: _images/admin07.png
  126. :alt: Fields have been reordered
  127. This isn't impressive with only two fields, but for admin forms with dozens
  128. of fields, choosing an intuitive order is an important usability detail.
  129. And speaking of forms with dozens of fields, you might want to split the form
  130. up into fieldsets:
  131. .. snippet::
  132. :filename: polls/admin.py
  133. from django.contrib import admin
  134. from polls.models import Question
  135. class QuestionAdmin(admin.ModelAdmin):
  136. fieldsets = [
  137. (None, {'fields': ['question_text']}),
  138. ('Date information', {'fields': ['pub_date']}),
  139. ]
  140. admin.site.register(Question, QuestionAdmin)
  141. The first element of each tuple in ``fieldsets`` is the title of the fieldset.
  142. Here's what our form looks like now:
  143. .. image:: _images/admin08t.png
  144. :alt: Form has fieldsets now
  145. You can assign arbitrary HTML classes to each fieldset. Django provides a
  146. ``"collapse"`` class that displays a particular fieldset initially collapsed.
  147. This is useful when you have a long form that contains a number of fields that
  148. aren't commonly used:
  149. .. snippet::
  150. :filename: polls/admin.py
  151. from django.contrib import admin
  152. from polls.models import Question
  153. class QuestionAdmin(admin.ModelAdmin):
  154. fieldsets = [
  155. (None, {'fields': ['question_text']}),
  156. ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
  157. ]
  158. .. image:: _images/admin09.png
  159. :alt: Fieldset is initially collapsed
  160. Adding related objects
  161. ======================
  162. OK, we have our Question admin page. But a ``Question`` has multiple ``Choices``, and
  163. the admin page doesn't display choices.
  164. Yet.
  165. There are two ways to solve this problem. The first is to register ``Choice``
  166. with the admin just as we did with ``Question``. That's easy:
  167. .. snippet::
  168. :filename: polls/admin.py
  169. from django.contrib import admin
  170. from polls.models import Choice
  171. admin.site.register(Choice)
  172. Now "Choices" is an available option in the Django admin. The "Add choice" form
  173. looks like this:
  174. .. image:: _images/admin10.png
  175. :alt: Choice admin page
  176. In that form, the "Question" field is a select box containing every question in the
  177. database. Django knows that a :class:`~django.db.models.ForeignKey` should be
  178. represented in the admin as a ``<select>`` box. In our case, only one question
  179. exists at this point.
  180. Also note the "Add Another" link next to "Question." Every object with a
  181. ``ForeignKey`` relationship to another gets this for free. When you click "Add
  182. Another," you'll get a popup window with the "Add question" form. If you add a question
  183. in that window and click "Save," Django will save the question to the database and
  184. dynamically add it as the selected choice on the "Add choice" form you're
  185. looking at.
  186. But, really, this is an inefficient way of adding ``Choice`` objects to the system.
  187. It'd be better if you could add a bunch of Choices directly when you create the
  188. ``Question`` object. Let's make that happen.
  189. Remove the ``register()`` call for the ``Choice`` model. Then, edit the ``Question``
  190. registration code to read:
  191. .. snippet::
  192. :filename: polls/admin.py
  193. from django.contrib import admin
  194. from polls.models import Choice, Question
  195. class ChoiceInline(admin.StackedInline):
  196. model = Choice
  197. extra = 3
  198. class QuestionAdmin(admin.ModelAdmin):
  199. fieldsets = [
  200. (None, {'fields': ['question_text']}),
  201. ('Date information', {'fields': ['pub_date'],
  202. 'classes': ['collapse']}),
  203. ]
  204. inlines = [ChoiceInline]
  205. admin.site.register(Question, QuestionAdmin)
  206. This tells Django: "``Choice`` objects are edited on the ``Question`` admin page. By
  207. default, provide enough fields for 3 choices."
  208. Load the "Add question" page to see how that looks:
  209. .. image:: _images/admin11t.png
  210. :alt: Add question page now has choices on it
  211. It works like this: There are three slots for related Choices -- as specified
  212. by ``extra`` -- and each time you come back to the "Change" page for an
  213. already-created object, you get another three extra slots.
  214. At the end of the three current slots you will find an "Add another Choice"
  215. link. If you click on it, a new slot will be added. If you want to remove the
  216. added slot, you can click on the X to the top right of the added slot. Note
  217. that you can't remove the original three slots. This image shows an added slot:
  218. .. image:: _images/admin15t.png
  219. :alt: Additional slot added dynamically
  220. One small problem, though. It takes a lot of screen space to display all the
  221. fields for entering related ``Choice`` objects. For that reason, Django offers a
  222. tabular way of displaying inline related objects; you just need to change
  223. the ``ChoiceInline`` declaration to read:
  224. .. snippet::
  225. :filename: polls/admin.py
  226. class ChoiceInline(admin.TabularInline):
  227. #...
  228. With that ``TabularInline`` (instead of ``StackedInline``), the
  229. related objects are displayed in a more compact, table-based format:
  230. .. image:: _images/admin12t.png
  231. :alt: Add question page now has more compact choices
  232. Note that there is an extra "Delete?" column that allows removing rows added
  233. using the "Add Another Choice" button and rows that have already been saved.
  234. Customize the admin change list
  235. ===============================
  236. Now that the Question admin page is looking good, let's make some tweaks to the
  237. "change list" page -- the one that displays all the questions in the system.
  238. Here's what it looks like at this point:
  239. .. image:: _images/admin04t.png
  240. :alt: Polls change list page
  241. By default, Django displays the ``str()`` of each object. But sometimes it'd be
  242. more helpful if we could display individual fields. To do that, use the
  243. ``list_display`` admin option, which is a tuple of field names to display, as
  244. columns, on the change list page for the object:
  245. .. snippet::
  246. :filename: polls/admin.py
  247. class QuestionAdmin(admin.ModelAdmin):
  248. # ...
  249. list_display = ('question_text', 'pub_date')
  250. Just for good measure, let's also include the ``was_published_recently`` custom
  251. method from Tutorial 1:
  252. .. snippet::
  253. :filename: polls/admin.py
  254. class QuestionAdmin(admin.ModelAdmin):
  255. # ...
  256. list_display = ('question_text', 'pub_date', 'was_published_recently')
  257. Now the question change list page looks like this:
  258. .. image:: _images/admin13t.png
  259. :alt: Polls change list page, updated
  260. You can click on the column headers to sort by those values -- except in the
  261. case of the ``was_published_recently`` header, because sorting by the output
  262. of an arbitrary method is not supported. Also note that the column header for
  263. ``was_published_recently`` is, by default, the name of the method (with
  264. underscores replaced with spaces), and that each line contains the string
  265. representation of the output.
  266. You can improve that by giving that method (in :file:`polls/models.py`) a few
  267. attributes, as follows:
  268. .. snippet::
  269. :filename: polls/admin.py
  270. class Question(models.Model):
  271. # ...
  272. def was_published_recently(self):
  273. return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
  274. was_published_recently.admin_order_field = 'pub_date'
  275. was_published_recently.boolean = True
  276. was_published_recently.short_description = 'Published recently?'
  277. Edit your :file:`polls/admin.py` file again and add an improvement to the Question
  278. change list page: Filters. Add the following line to ``QuestionAdmin``::
  279. list_filter = ['pub_date']
  280. That adds a "Filter" sidebar that lets people filter the change list by the
  281. ``pub_date`` field:
  282. .. image:: _images/admin14t.png
  283. :alt: Polls change list page, updated
  284. The type of filter displayed depends on the type of field you're filtering on.
  285. Because ``pub_date`` is a :class:`~django.db.models.DateTimeField`, Django
  286. knows to give appropriate filter options: "Any date," "Today," "Past 7 days,"
  287. "This month," "This year."
  288. This is shaping up well. Let's add some search capability::
  289. search_fields = ['question_text']
  290. That adds a search box at the top of the change list. When somebody enters
  291. search terms, Django will search the ``question_text`` field. You can use as many
  292. fields as you'd like -- although because it uses a ``LIKE`` query behind the
  293. scenes, keep it reasonable, to keep your database happy.
  294. Now's also a good time to note that change lists give you free pagination. The
  295. default is to display 100 items per page. Change-list pagination, search boxes,
  296. filters, date-hierarchies and column-header-ordering all work together like you
  297. think they should.
  298. Customize the admin look and feel
  299. =================================
  300. Clearly, having "Django administration" at the top of each admin page is
  301. ridiculous. It's just placeholder text.
  302. That's easy to change, though, using Django's template system. The Django admin
  303. is powered by Django itself, and its interfaces use Django's own template
  304. system.
  305. .. _ref-customizing-your-projects-templates:
  306. Customizing your *project's* templates
  307. --------------------------------------
  308. Create a ``templates`` directory in your project directory. Templates can
  309. live anywhere on your filesystem that Django can access. (Django runs as
  310. whatever user your server runs.) However, keeping your templates within the
  311. project is a good convention to follow.
  312. Open your settings file (:file:`mysite/settings.py`, remember) and add a
  313. :setting:`TEMPLATE_DIRS` setting:
  314. .. snippet::
  315. :filename: mysite/settings.py
  316. TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
  317. :setting:`TEMPLATE_DIRS` is an iterable of filesystem directories to check when
  318. loading Django templates; it's a search path.
  319. Now create a directory called ``admin`` inside ``templates``, and copy the
  320. template ``admin/base_site.html`` from within the default Django admin
  321. template directory in the source code of Django itself
  322. (``django/contrib/admin/templates``) into that directory.
  323. .. admonition:: Where are the Django source files?
  324. If you have difficulty finding where the Django source files are located
  325. on your system, run the following command:
  326. .. code-block:: bash
  327. python -c "
  328. import sys
  329. sys.path = sys.path[1:]
  330. import django
  331. print(django.__path__)"
  332. Then, just edit the file and replace ``{{ site_header }}`` with your own
  333. site's name as you see fit. We use this approach to teach you how to override
  334. templates. In an actual project, you would probably use the
  335. :attr:`django.contrib.admin.AdminSite.site_header` attribute to more easily
  336. make this particular customization.
  337. This template file contains lots of text like ``{% block branding %}``
  338. and ``{{ title }}``. The ``{%`` and ``{{`` tags are part of Django's
  339. template language. When Django renders ``admin/base_site.html``, this
  340. template language will be evaluated to produce the final HTML page.
  341. Don't worry if you can't make any sense of the template right now --
  342. we'll delve into Django's templating language in Tutorial 3.
  343. Note that any of Django's default admin templates can be overridden. To
  344. override a template, just do the same thing you did with ``base_site.html`` --
  345. copy it from the default directory into your custom directory, and make
  346. changes.
  347. Customizing your *application's* templates
  348. ------------------------------------------
  349. Astute readers will ask: But if :setting:`TEMPLATE_DIRS` was empty by default,
  350. how was Django finding the default admin templates? The answer is that, by
  351. default, Django automatically looks for a ``templates/`` subdirectory within
  352. each application package, for use as a fallback (don't forget that
  353. ``django.contrib.admin`` is an application).
  354. Our poll application is not very complex and doesn't need custom admin
  355. templates. But if it grew more sophisticated and required modification of
  356. Django's standard admin templates for some of its functionality, it would be
  357. more sensible to modify the *application's* templates, rather than those in the
  358. *project*. That way, you could include the polls application in any new project
  359. and be assured that it would find the custom templates it needed.
  360. See the :ref:`template loader documentation <template-loaders>` for more
  361. information about how Django finds its templates.
  362. Customize the admin index page
  363. ==============================
  364. On a similar note, you might want to customize the look and feel of the Django
  365. admin index page.
  366. By default, it displays all the apps in :setting:`INSTALLED_APPS` that have been
  367. registered with the admin application, in alphabetical order. You may want to
  368. make significant changes to the layout. After all, the index is probably the
  369. most important page of the admin, and it should be easy to use.
  370. The template to customize is ``admin/index.html``. (Do the same as with
  371. ``admin/base_site.html`` in the previous section -- copy it from the default
  372. directory to your custom template directory.) Edit the file, and you'll see it
  373. uses a template variable called ``app_list``. That variable contains every
  374. installed Django app. Instead of using that, you can hard-code links to
  375. object-specific admin pages in whatever way you think is best. Again,
  376. don't worry if you can't understand the template language -- we'll cover that
  377. in more detail in Tutorial 3.
  378. When you're comfortable with the admin site, read :doc:`part 3 of this tutorial
  379. </intro/tutorial03>` to start working on public poll views.