tutorial07.txt 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. =====================================
  2. Writing your first Django app, part 7
  3. =====================================
  4. This tutorial begins where :doc:`Tutorial 6 </intro/tutorial06>` left off. We're
  5. continuing the Web-poll application and will focus on customizing the Django's
  6. automatically-generated admin site that we first explored in :doc:`Tutorial 2
  7. </intro/tutorial02>`.
  8. Customize the admin form
  9. ========================
  10. By registering the ``Question`` model with ``admin.site.register(Question)``,
  11. Django was able to construct a default form representation. Often, you'll want
  12. to customize how the admin form looks and works. You'll do this by telling
  13. Django the options you want when you register the object.
  14. Let's see how this works by reordering the fields on the edit form. Replace
  15. the ``admin.site.register(Question)`` line with:
  16. .. snippet::
  17. :filename: polls/admin.py
  18. from django.contrib import admin
  19. from .models import Question
  20. class QuestionAdmin(admin.ModelAdmin):
  21. fields = ['pub_date', 'question_text']
  22. admin.site.register(Question, QuestionAdmin)
  23. You'll follow this pattern -- create a model admin class, then pass it as the
  24. second argument to ``admin.site.register()`` -- any time you need to change the
  25. admin options for an model.
  26. This particular change above makes the "Publication date" come before the
  27. "Question" field:
  28. .. image:: _images/admin07.png
  29. :alt: Fields have been reordered
  30. This isn't impressive with only two fields, but for admin forms with dozens
  31. of fields, choosing an intuitive order is an important usability detail.
  32. And speaking of forms with dozens of fields, you might want to split the form
  33. up into fieldsets:
  34. .. snippet::
  35. :filename: polls/admin.py
  36. from django.contrib import admin
  37. from .models import Question
  38. class QuestionAdmin(admin.ModelAdmin):
  39. fieldsets = [
  40. (None, {'fields': ['question_text']}),
  41. ('Date information', {'fields': ['pub_date']}),
  42. ]
  43. admin.site.register(Question, QuestionAdmin)
  44. The first element of each tuple in
  45. :attr:`~django.contrib.admin.ModelAdmin.fieldsets` is the title of the fieldset.
  46. Here's what our form looks like now:
  47. .. image:: _images/admin08t.png
  48. :alt: Form has fieldsets now
  49. Adding related objects
  50. ======================
  51. OK, we have our Question admin page, but a ``Question`` has multiple
  52. ``Choice``\s, and the admin page doesn't display choices.
  53. Yet.
  54. There are two ways to solve this problem. The first is to register ``Choice``
  55. with the admin just as we did with ``Question``. That's easy:
  56. .. snippet::
  57. :filename: polls/admin.py
  58. from django.contrib import admin
  59. from .models import Choice, Question
  60. # ...
  61. admin.site.register(Choice)
  62. Now "Choices" is an available option in the Django admin. The "Add choice" form
  63. looks like this:
  64. .. image:: _images/admin09.png
  65. :alt: Choice admin page
  66. In that form, the "Question" field is a select box containing every question in the
  67. database. Django knows that a :class:`~django.db.models.ForeignKey` should be
  68. represented in the admin as a ``<select>`` box. In our case, only one question
  69. exists at this point.
  70. Also note the "Add Another" link next to "Question." Every object with a
  71. ``ForeignKey`` relationship to another gets this for free. When you click "Add
  72. Another", you'll get a popup window with the "Add question" form. If you add a question
  73. in that window and click "Save", Django will save the question to the database and
  74. dynamically add it as the selected choice on the "Add choice" form you're
  75. looking at.
  76. But, really, this is an inefficient way of adding ``Choice`` objects to the system.
  77. It'd be better if you could add a bunch of Choices directly when you create the
  78. ``Question`` object. Let's make that happen.
  79. Remove the ``register()`` call for the ``Choice`` model. Then, edit the ``Question``
  80. registration code to read:
  81. .. snippet::
  82. :filename: polls/admin.py
  83. from django.contrib import admin
  84. from .models import Choice, Question
  85. class ChoiceInline(admin.StackedInline):
  86. model = Choice
  87. extra = 3
  88. class QuestionAdmin(admin.ModelAdmin):
  89. fieldsets = [
  90. (None, {'fields': ['question_text']}),
  91. ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
  92. ]
  93. inlines = [ChoiceInline]
  94. admin.site.register(Question, QuestionAdmin)
  95. This tells Django: "``Choice`` objects are edited on the ``Question`` admin page. By
  96. default, provide enough fields for 3 choices."
  97. Load the "Add question" page to see how that looks:
  98. .. image:: _images/admin10t.png
  99. :alt: Add question page now has choices on it
  100. It works like this: There are three slots for related Choices -- as specified
  101. by ``extra`` -- and each time you come back to the "Change" page for an
  102. already-created object, you get another three extra slots.
  103. At the end of the three current slots you will find an "Add another Choice"
  104. link. If you click on it, a new slot will be added. If you want to remove the
  105. added slot, you can click on the X to the top right of the added slot. Note
  106. that you can't remove the original three slots. This image shows an added slot:
  107. .. image:: _images/admin14t.png
  108. :alt: Additional slot added dynamically
  109. One small problem, though. It takes a lot of screen space to display all the
  110. fields for entering related ``Choice`` objects. For that reason, Django offers a
  111. tabular way of displaying inline related objects; you just need to change
  112. the ``ChoiceInline`` declaration to read:
  113. .. snippet::
  114. :filename: polls/admin.py
  115. class ChoiceInline(admin.TabularInline):
  116. #...
  117. With that ``TabularInline`` (instead of ``StackedInline``), the
  118. related objects are displayed in a more compact, table-based format:
  119. .. image:: _images/admin11t.png
  120. :alt: Add question page now has more compact choices
  121. Note that there is an extra "Delete?" column that allows removing rows added
  122. using the "Add Another Choice" button and rows that have already been saved.
  123. Customize the admin change list
  124. ===============================
  125. Now that the Question admin page is looking good, let's make some tweaks to the
  126. "change list" page -- the one that displays all the questions in the system.
  127. Here's what it looks like at this point:
  128. .. image:: _images/admin04t.png
  129. :alt: Polls change list page
  130. By default, Django displays the ``str()`` of each object. But sometimes it'd be
  131. more helpful if we could display individual fields. To do that, use the
  132. :attr:`~django.contrib.admin.ModelAdmin.list_display` admin option, which is a
  133. tuple of field names to display, as columns, on the change list page for the
  134. object:
  135. .. snippet::
  136. :filename: polls/admin.py
  137. class QuestionAdmin(admin.ModelAdmin):
  138. # ...
  139. list_display = ('question_text', 'pub_date')
  140. Just for good measure, let's also include the ``was_published_recently()``
  141. method from :doc:`Tutorial 2 </intro/tutorial02>`:
  142. .. snippet::
  143. :filename: polls/admin.py
  144. class QuestionAdmin(admin.ModelAdmin):
  145. # ...
  146. list_display = ('question_text', 'pub_date', 'was_published_recently')
  147. Now the question change list page looks like this:
  148. .. image:: _images/admin12t.png
  149. :alt: Polls change list page, updated
  150. You can click on the column headers to sort by those values -- except in the
  151. case of the ``was_published_recently`` header, because sorting by the output
  152. of an arbitrary method is not supported. Also note that the column header for
  153. ``was_published_recently`` is, by default, the name of the method (with
  154. underscores replaced with spaces), and that each line contains the string
  155. representation of the output.
  156. You can improve that by giving that method (in :file:`polls/models.py`) a few
  157. attributes, as follows:
  158. .. snippet::
  159. :filename: polls/models.py
  160. class Question(models.Model):
  161. # ...
  162. def was_published_recently(self):
  163. return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
  164. was_published_recently.admin_order_field = 'pub_date'
  165. was_published_recently.boolean = True
  166. was_published_recently.short_description = 'Published recently?'
  167. For more information on these method properties, see
  168. :attr:`~django.contrib.admin.ModelAdmin.list_display`.
  169. Edit your :file:`polls/admin.py` file again and add an improvement to the
  170. ``Question`` change list page: filters using the
  171. :attr:`~django.contrib.admin.ModelAdmin.list_filter`. Add the following line to
  172. ``QuestionAdmin``::
  173. list_filter = ['pub_date']
  174. That adds a "Filter" sidebar that lets people filter the change list by the
  175. ``pub_date`` field:
  176. .. image:: _images/admin13t.png
  177. :alt: Polls change list page, updated
  178. The type of filter displayed depends on the type of field you're filtering on.
  179. Because ``pub_date`` is a :class:`~django.db.models.DateTimeField`, Django
  180. knows to give appropriate filter options: "Any date", "Today", "Past 7 days",
  181. "This month", "This year".
  182. This is shaping up well. Let's add some search capability::
  183. search_fields = ['question_text']
  184. That adds a search box at the top of the change list. When somebody enters
  185. search terms, Django will search the ``question_text`` field. You can use as many
  186. fields as you'd like -- although because it uses a ``LIKE`` query behind the
  187. scenes, limiting the number of search fields to a reasonable number will make
  188. it easier for your database to do the search.
  189. Now's also a good time to note that change lists give you free pagination. The
  190. default is to display 100 items per page. :attr:`Change list pagination
  191. <django.contrib.admin.ModelAdmin.list_per_page>`, :attr:`search boxes
  192. <django.contrib.admin.ModelAdmin.search_fields>`, :attr:`filters
  193. <django.contrib.admin.ModelAdmin.list_filter>`, :attr:`date-hierarchies
  194. <django.contrib.admin.ModelAdmin.date_hierarchy>`, and
  195. :attr:`column-header-ordering <django.contrib.admin.ModelAdmin.list_display>`
  196. all work together like you think they should.
  197. Customize the admin look and feel
  198. =================================
  199. Clearly, having "Django administration" at the top of each admin page is
  200. ridiculous. It's just placeholder text.
  201. That's easy to change, though, using Django's template system. The Django admin
  202. is powered by Django itself, and its interfaces use Django's own template
  203. system.
  204. .. _ref-customizing-your-projects-templates:
  205. Customizing your *project's* templates
  206. --------------------------------------
  207. Create a ``templates`` directory in your project directory (the one that
  208. contains ``manage.py``). Templates can live anywhere on your filesystem that
  209. Django can access. (Django runs as whatever user your server runs.) However,
  210. keeping your templates within the project is a good convention to follow.
  211. Open your settings file (:file:`mysite/settings.py`, remember) and add a
  212. :setting:`DIRS <TEMPLATES-DIRS>` option in the :setting:`TEMPLATES` setting:
  213. .. snippet::
  214. :filename: mysite/settings.py
  215. TEMPLATES = [
  216. {
  217. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  218. 'DIRS': [os.path.join(BASE_DIR, 'templates')],
  219. 'APP_DIRS': True,
  220. 'OPTIONS': {
  221. 'context_processors': [
  222. 'django.template.context_processors.debug',
  223. 'django.template.context_processors.request',
  224. 'django.contrib.auth.context_processors.auth',
  225. 'django.contrib.messages.context_processors.messages',
  226. ],
  227. },
  228. },
  229. ]
  230. :setting:`DIRS <TEMPLATES-DIRS>` is a list of filesystem directories to check
  231. when loading Django templates; it's a search path.
  232. .. admonition:: Organizing templates
  233. Just like the static files, we *could* have all our templates together, in
  234. one big templates directory, and it would work perfectly well. However,
  235. templates that belongs to a particular application, we should put in the
  236. application’s template directory (e.g. ``polls/templates``) rather than the
  237. project’s (``templates``). We'll discuss in more detail in the
  238. :doc:`reusable apps tutorial </intro/reusable-apps>` *why* we do this.
  239. Now create a directory called ``admin`` inside ``templates``, and copy the
  240. template ``admin/base_site.html`` from within the default Django admin
  241. template directory in the source code of Django itself
  242. (``django/contrib/admin/templates``) into that directory.
  243. .. admonition:: Where are the Django source files?
  244. If you have difficulty finding where the Django source files are located
  245. on your system, run the following command:
  246. .. code-block:: console
  247. $ python -c "import django; print(django.__path__)"
  248. Then, just edit the file and replace
  249. ``{{ site_header|default:_('Django administration') }}`` (including the curly
  250. braces) with your own site's name as you see fit. You should end up with
  251. a section of code like:
  252. .. code-block:: html+django
  253. {% block branding %}
  254. <h1 id="site-name"><a href="{% url 'admin:index' %}">Polls Administration</a></h1>
  255. {% endblock %}
  256. We use this approach to teach you how to override templates. In an actual
  257. project, you would probably use
  258. the :attr:`django.contrib.admin.AdminSite.site_header` attribute to more easily
  259. make this particular customization.
  260. This template file contains lots of text like ``{% block branding %}``
  261. and ``{{ title }}``. The ``{%`` and ``{{`` tags are part of Django's
  262. template language. When Django renders ``admin/base_site.html``, this
  263. template language will be evaluated to produce the final HTML page, just like
  264. we saw in :doc:`Tutorial 3 </intro/tutorial03>`.
  265. Note that any of Django's default admin templates can be overridden. To
  266. override a template, just do the same thing you did with ``base_site.html`` --
  267. copy it from the default directory into your custom directory, and make
  268. changes.
  269. Customizing your *application's* templates
  270. ------------------------------------------
  271. Astute readers will ask: But if :setting:`DIRS <TEMPLATES-DIRS>` was empty by
  272. default, how was Django finding the default admin templates? The answer is
  273. that, since :setting:`APP_DIRS <TEMPLATES-APP_DIRS>` is set to ``True``,
  274. Django automatically looks for a ``templates/`` subdirectory within each
  275. application package, for use as a fallback (don't forget that
  276. ``django.contrib.admin`` is an application).
  277. Our poll application is not very complex and doesn't need custom admin
  278. templates. But if it grew more sophisticated and required modification of
  279. Django's standard admin templates for some of its functionality, it would be
  280. more sensible to modify the *application's* templates, rather than those in the
  281. *project*. That way, you could include the polls application in any new project
  282. and be assured that it would find the custom templates it needed.
  283. See the :ref:`template loading documentation <template-loading>` for more
  284. information about how Django finds its templates.
  285. Customize the admin index page
  286. ==============================
  287. On a similar note, you might want to customize the look and feel of the Django
  288. admin index page.
  289. By default, it displays all the apps in :setting:`INSTALLED_APPS` that have been
  290. registered with the admin application, in alphabetical order. You may want to
  291. make significant changes to the layout. After all, the index is probably the
  292. most important page of the admin, and it should be easy to use.
  293. The template to customize is ``admin/index.html``. (Do the same as with
  294. ``admin/base_site.html`` in the previous section -- copy it from the default
  295. directory to your custom template directory). Edit the file, and you'll see it
  296. uses a template variable called ``app_list``. That variable contains every
  297. installed Django app. Instead of using that, you can hard-code links to
  298. object-specific admin pages in whatever way you think is best.
  299. What's next?
  300. ============
  301. The beginner tutorial ends here. In the meantime, you might want to check out
  302. some pointers on :doc:`where to go from here </intro/whatsnext>`.
  303. If you are familiar with Python packaging and interested in learning how to
  304. turn polls into a "reusable app", check out :doc:`Advanced tutorial: How to
  305. write reusable apps</intro/reusable-apps>`.