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