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