2
0

tutorial07.txt 16 KB

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