tutorial02.txt 22 KB

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