tutorial.rst 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. Your first Wagtail site
  2. =======================
  3. .. note::
  4. This tutorial covers setting up a brand new Wagtail project. If you'd like to add Wagtail to an existing Django project instead, see :doc:`integrating_into_django`.
  5. 1. Install Wagtail and its dependencies:
  6. .. code-block:: console
  7. $ pip install wagtail
  8. 2. Start your site:
  9. .. code-block:: console
  10. $ wagtail start mysite
  11. $ cd mysite
  12. Wagtail provides a ``start`` command similar to
  13. ``django-admin.py startproject``. Running ``wagtail start mysite`` in
  14. your project will generate a new ``mysite`` folder with a few
  15. Wagtail-specific extras, including the required project settings, a
  16. "home" app with a blank ``HomePage`` model and basic templates and a sample
  17. "search" app.
  18. 3. Install project dependencies:
  19. .. code-block:: console
  20. $ pip install -r requirements.txt
  21. This ensures that you have the relevant version of Django for the project you've just created.
  22. 4. Create the database:
  23. .. code-block:: console
  24. $ python manage.py migrate
  25. If you haven't updated the project settings, this will be a SQLite
  26. database file in the project directory.
  27. 5. Create an admin user:
  28. .. code-block:: console
  29. $ python manage.py createsuperuser
  30. 6. Start the server:
  31. .. code-block:: console
  32. $ python manage.py runserver
  33. If everything worked, http://127.0.0.1:8000 will show you a welcome page:
  34. .. figure:: ../_static/images/tutorial/tutorial_1.png
  35. :alt: Wagtail welcome message
  36. You can now access the administrative area at http://127.0.0.1:8000/admin
  37. .. figure:: ../_static/images/tutorial/tutorial_2.png
  38. :alt: Administrative screen
  39. Extend the HomePage model
  40. -------------------------
  41. Out of the box, the "home" app defines a blank ``HomePage`` model in ``models.py``, along with a migration that creates a homepage and configures Wagtail to use it.
  42. Edit ``home/models.py`` as follows, to add a ``body`` field to the model:
  43. .. code-block:: python
  44. from django.db import models
  45. from wagtail.core.models import Page
  46. from wagtail.core.fields import RichTextField
  47. from wagtail.admin.edit_handlers import FieldPanel
  48. class HomePage(Page):
  49. body = RichTextField(blank=True)
  50. content_panels = Page.content_panels + [
  51. FieldPanel('body', classname="full"),
  52. ]
  53. ``body`` is defined as ``RichTextField``, a special Wagtail field. You
  54. can use any of the `Django core fields <https://docs.djangoproject.com/en/stable/ref/models/fields/>`__. ``content_panels`` define the
  55. capabilities and the layout of the editing interface. :doc:`More on creating Page models. <../topics/pages>`
  56. Run ``python manage.py makemigrations``, then
  57. ``python manage.py migrate`` to update the database with your model
  58. changes. You must run the above commands each time you make changes to
  59. the model definition.
  60. You can now edit the homepage within the Wagtail admin area (go to Pages, Homepage, then Edit) to see the new body field. Enter some text into the body field, and publish the page.
  61. The page template now needs to be updated to reflect the changes made
  62. to the model. Wagtail uses normal Django templates to render each page
  63. type. By default, it will look for a template filename formed from the app and model name,
  64. separating capital letters with underscores (e.g. HomePage within the 'home' app becomes
  65. ``home/home_page.html``). This template file can exist in any location recognised by
  66. `Django's template rules <https://docs.djangoproject.com/en/stable/intro/tutorial03/#write-views-that-actually-do-something>`__; conventionally it is placed under a ``templates`` folder within the app.
  67. Edit ``home/templates/home/home_page.html`` to contain the following:
  68. .. code-block:: html+django
  69. {% extends "base.html" %}
  70. {% load wagtailcore_tags %}
  71. {% block body_class %}template-homepage{% endblock %}
  72. {% block content %}
  73. {{ page.body|richtext }}
  74. {% endblock %}
  75. .. figure:: ../_static/images/tutorial/tutorial_3.png
  76. :alt: Updated homepage
  77. Wagtail template tags
  78. ~~~~~~~~~~~~~~~~~~~~~
  79. Wagtail provides a number of :ref:`template tags & filters <template-tags-and-filters>`
  80. which can be loaded by including ``{% load wagtailcore_tags %}`` at the top of
  81. your template file.
  82. In this tutorial, we use the `richtext` filter to escape and print the contents
  83. of a ``RichTextField``:
  84. .. code-block:: html+django
  85. {% load wagtailcore_tags %}
  86. {{ page.body|richtext }}
  87. Produces:
  88. .. code-block:: html
  89. <div class="rich-text">
  90. <p>
  91. <b>Welcome</b> to our new site!
  92. </p>
  93. </div>
  94. **Note:** You'll need to include ``{% load wagtailcore_tags %}`` in each
  95. template that uses Wagtail's tags. Django will throw a ``TemplateSyntaxError``
  96. if the tags aren't loaded.
  97. A basic blog
  98. ------------
  99. We are now ready to create a blog. To do so, run
  100. ``python manage.py startapp blog`` to create a new app in your Wagtail site.
  101. Add the new ``blog`` app to ``INSTALLED_APPS`` in ``mysite/settings/base.py``.
  102. Blog Index and Posts
  103. ~~~~~~~~~~~~~~~~~~~~
  104. Lets start with a simple index page for our blog. In ``blog/models.py``:
  105. .. code-block:: python
  106. from wagtail.core.models import Page
  107. from wagtail.core.fields import RichTextField
  108. from wagtail.admin.edit_handlers import FieldPanel
  109. class BlogIndexPage(Page):
  110. intro = RichTextField(blank=True)
  111. content_panels = Page.content_panels + [
  112. FieldPanel('intro', classname="full")
  113. ]
  114. Run ``python manage.py makemigrations`` and ``python manage.py migrate``.
  115. Since the model is called ``BlogIndexPage``, the default template name
  116. (unless we override it) will be ``blog/templates/blog/blog_index_page.html``. Create this file
  117. with the following content:
  118. .. code-block:: html+django
  119. {% extends "base.html" %}
  120. {% load wagtailcore_tags %}
  121. {% block body_class %}template-blogindexpage{% endblock %}
  122. {% block content %}
  123. <h1>{{ page.title }}</h1>
  124. <div class="intro">{{ page.intro|richtext }}</div>
  125. {% for post in page.get_children %}
  126. <h2><a href="{% pageurl post %}">{{ post.title }}</a></h2>
  127. {{ post.specific.intro }}
  128. {{ post.specific.body|richtext }}
  129. {% endfor %}
  130. {% endblock %}
  131. Most of this should be familiar, but we'll explain ``get_children`` a bit later.
  132. Note the ``pageurl`` tag, which is similar to Django's ``url`` tag but
  133. takes a Wagtail Page object as an argument.
  134. In the Wagtail admin, create a ``BlogIndexPage`` as a child of the Homepage,
  135. make sure it has the slug "blog" on the Promote tab, and publish it.
  136. You should now be able to access the url ``/blog`` on your site
  137. (note how the slug from the Promote tab defines the page URL).
  138. Now we need a model and template for our blog posts. In ``blog/models.py``:
  139. .. code-block:: python
  140. from django.db import models
  141. from wagtail.core.models import Page
  142. from wagtail.core.fields import RichTextField
  143. from wagtail.admin.edit_handlers import FieldPanel
  144. from wagtail.search import index
  145. # Keep the definition of BlogIndexPage, and add:
  146. class BlogPage(Page):
  147. date = models.DateField("Post date")
  148. intro = models.CharField(max_length=250)
  149. body = RichTextField(blank=True)
  150. search_fields = Page.search_fields + [
  151. index.SearchField('intro'),
  152. index.SearchField('body'),
  153. ]
  154. content_panels = Page.content_panels + [
  155. FieldPanel('date'),
  156. FieldPanel('intro'),
  157. FieldPanel('body', classname="full"),
  158. ]
  159. Run ``python manage.py makemigrations`` and ``python manage.py migrate``.
  160. Create a template at ``blog/templates/blog/blog_page.html``:
  161. .. code-block:: html+django
  162. {% extends "base.html" %}
  163. {% load wagtailcore_tags %}
  164. {% block body_class %}template-blogpage{% endblock %}
  165. {% block content %}
  166. <h1>{{ page.title }}</h1>
  167. <p class="meta">{{ page.date }}</p>
  168. <div class="intro">{{ page.intro }}</div>
  169. {{ page.body|richtext }}
  170. <p><a href="{{ page.get_parent.url }}">Return to blog</a></p>
  171. {% endblock %}
  172. Note the use of Wagtail's built-in ``get_parent()`` method to obtain the
  173. URL of the blog this post is a part of.
  174. Now create a few blog posts as children of ``BlogIndexPage``.
  175. Be sure to select type "Blog Page" when creating your posts.
  176. .. figure:: ../_static/images/tutorial/tutorial_4a.png
  177. :alt: Create blog post as child of BlogIndex
  178. .. figure:: ../_static/images/tutorial/tutorial_4b.png
  179. :alt: Choose type BlogPost
  180. Wagtail gives you full control over what kinds of content can be created under
  181. various parent content types. By default, any page type can be a child of any
  182. other page type.
  183. .. figure:: ../_static/images/tutorial/tutorial_5.png
  184. :alt: Page edit screen
  185. You should now have the very beginnings of a working blog.
  186. Access the ``/blog`` URL and you should see something like this:
  187. .. figure:: ../_static/images/tutorial/tutorial_7.png
  188. :alt: Blog basics
  189. Titles should link to post pages, and a link back to the blog's
  190. homepage should appear in the footer of each post page.
  191. Parents and Children
  192. ~~~~~~~~~~~~~~~~~~~~
  193. Much of the work you'll be doing in Wagtail revolves around the concept of hierarchical
  194. "tree" structures consisting of nodes and leaves (see :doc:`../reference/pages/theory`).
  195. In this case, the ``BlogIndexPage`` is a "node" and individual ``BlogPage`` instances
  196. are the "leaves".
  197. Take another look at the guts of ``blog_index_page.html``:
  198. .. code-block:: html+django
  199. {% for post in page.get_children %}
  200. <h2><a href="{% pageurl post %}">{{ post.title }}</a></h2>
  201. {{ post.specific.intro }}
  202. {{ post.specific.body|richtext }}
  203. {% endfor %}
  204. Every "page" in Wagtail can call out to its parent or children
  205. from its own position in the hierarchy. But why do we have to
  206. specify ``post.specific.intro`` rather than ``post.intro``?
  207. This has to do with the way we defined our model:
  208. ``class BlogPage(Page):``
  209. The ``get_children()`` method gets us a list of instances of the ``Page`` base class.
  210. When we want to reference properties of the instances that inherit from the base class,
  211. Wagtail provides the ``specific`` method that retrieves the actual ``BlogPage`` record.
  212. While the "title" field is present on the base ``Page`` model, "intro" is only present
  213. on the ``BlogPage`` model, so we need ``.specific`` to access it.
  214. To tighten up template code like this, we could use Django's ``with`` tag:
  215. .. code-block:: html+django
  216. {% for post in page.get_children %}
  217. {% with post=post.specific %}
  218. <h2><a href="{% pageurl post %}">{{ post.title }}</a></h2>
  219. <p>{{ post.intro }}</p>
  220. {{ post.body|richtext }}
  221. {% endwith %}
  222. {% endfor %}
  223. When you start writing more customized Wagtail code, you'll find a whole set of QuerySet
  224. modifiers to help you navigate the hierarchy.
  225. .. code-block:: python
  226. # Given a page object 'somepage':
  227. MyModel.objects.descendant_of(somepage)
  228. child_of(page) / not_child_of(somepage)
  229. ancestor_of(somepage) / not_ancestor_of(somepage)
  230. parent_of(somepage) / not_parent_of(somepage)
  231. sibling_of(somepage) / not_sibling_of(somepage)
  232. # ... and ...
  233. somepage.get_children()
  234. somepage.get_ancestors()
  235. somepage.get_descendants()
  236. somepage.get_siblings()
  237. For more information, see: :doc:`../reference/pages/queryset_reference`
  238. Overriding Context
  239. ~~~~~~~~~~~~~~~~~~
  240. There are a couple of problems with our blog index view:
  241. 1) Blogs generally display content in *reverse* chronological order
  242. 2) We want to make sure we're only displaying *published* content.
  243. To accomplish these things, we need to do more than just grab the index
  244. page's children in the template. Instead, we'll want to modify the
  245. QuerySet in the model definition. Wagtail makes this possible via
  246. the overridable ``get_context()`` method. Modify your ``BlogIndexPage``
  247. model like this:
  248. .. code-block:: python
  249. class BlogIndexPage(Page):
  250. intro = RichTextField(blank=True)
  251. def get_context(self, request):
  252. # Update context to include only published posts, ordered by reverse-chron
  253. context = super().get_context(request)
  254. blogpages = self.get_children().live().order_by('-first_published_at')
  255. context['blogpages'] = blogpages
  256. return context
  257. All we've done here is retrieve the original context, create a custom QuerySet,
  258. add it to the retrieved context, and return the modified context back to the view.
  259. You'll also need to modify your ``blog_index_page.html`` template slightly.
  260. Change:
  261. ``{% for post in page.get_children %}`` to ``{% for post in blogpages %}``
  262. Now try unpublishing one of your posts - it should disappear from the blog index
  263. page. The remaining posts should now be sorted with the most recently published
  264. posts first.
  265. Images
  266. ~~~~~~
  267. Let's add the ability to attach an image gallery to our blog posts. While it's possible to simply insert images into the ``body`` rich text field, there are several advantages to setting up our gallery images as a new dedicated object type within the database - this way, you have full control of the layout and styling of the images on the template, rather than having to lay them out in a particular way within the rich text field. It also makes it possible for the images to be used elsewhere, independently of the blog text - for example, displaying a thumbnail on the blog index page.
  268. Add a new ``BlogPageGalleryImage`` model to ``models.py``:
  269. .. code-block:: python
  270. from django.db import models
  271. # New imports added for ParentalKey, Orderable, InlinePanel, ImageChooserPanel
  272. from modelcluster.fields import ParentalKey
  273. from wagtail.core.models import Page, Orderable
  274. from wagtail.core.fields import RichTextField
  275. from wagtail.admin.edit_handlers import FieldPanel, InlinePanel
  276. from wagtail.images.edit_handlers import ImageChooserPanel
  277. from wagtail.search import index
  278. # ... (Keep the definition of BlogIndexPage, and update BlogPage:)
  279. class BlogPage(Page):
  280. date = models.DateField("Post date")
  281. intro = models.CharField(max_length=250)
  282. body = RichTextField(blank=True)
  283. search_fields = Page.search_fields + [
  284. index.SearchField('intro'),
  285. index.SearchField('body'),
  286. ]
  287. content_panels = Page.content_panels + [
  288. FieldPanel('date'),
  289. FieldPanel('intro'),
  290. FieldPanel('body', classname="full"),
  291. InlinePanel('gallery_images', label="Gallery images"),
  292. ]
  293. class BlogPageGalleryImage(Orderable):
  294. page = ParentalKey(BlogPage, on_delete=models.CASCADE, related_name='gallery_images')
  295. image = models.ForeignKey(
  296. 'wagtailimages.Image', on_delete=models.CASCADE, related_name='+'
  297. )
  298. caption = models.CharField(blank=True, max_length=250)
  299. panels = [
  300. ImageChooserPanel('image'),
  301. FieldPanel('caption'),
  302. ]
  303. Run ``python manage.py makemigrations`` and ``python manage.py migrate``.
  304. There are a few new concepts here, so let's take them one at a time:
  305. Inheriting from ``Orderable`` adds a ``sort_order`` field to the model, to keep track of the ordering of images in the gallery.
  306. The ``ParentalKey`` to ``BlogPage`` is what attaches the gallery images to a specific page. A ``ParentalKey`` works similarly to a ``ForeignKey``, but also defines ``BlogPageGalleryImage`` as a "child" of the ``BlogPage`` model, so that it's treated as a fundamental part of the page in operations like submitting for moderation, and tracking revision history.
  307. ``image`` is a ``ForeignKey`` to Wagtail's built-in ``Image`` model, where the images themselves are stored. This comes with a dedicated panel type, ``ImageChooserPanel``, which provides a pop-up interface for choosing an existing image or uploading a new one. This way, we allow an image to exist in multiple galleries - effectively, we've created a many-to-many relationship between pages and images.
  308. Specifying ``on_delete=models.CASCADE`` on the foreign key means that if the image is deleted from the system, the gallery entry is deleted as well. (In other situations, it might be appropriate to leave the entry in place - for example, if an "our staff" page included a list of people with headshots, and one of those photos was deleted, we'd rather leave the person in place on the page without a photo. In this case, we'd set the foreign key to ``blank=True, null=True, on_delete=models.SET_NULL``.)
  309. Finally, adding the ``InlinePanel`` to ``BlogPage.content_panels`` makes the gallery images available on the editing interface for ``BlogPage``.
  310. Adjust your blog page template to include the images:
  311. .. code-block:: html+django
  312. {% extends "base.html" %}
  313. {% load wagtailcore_tags wagtailimages_tags %}
  314. {% block body_class %}template-blogpage{% endblock %}
  315. {% block content %}
  316. <h1>{{ page.title }}</h1>
  317. <p class="meta">{{ page.date }}</p>
  318. <div class="intro">{{ page.intro }}</div>
  319. {{ page.body|richtext }}
  320. {% for item in page.gallery_images.all %}
  321. <div style="float: left; margin: 10px">
  322. {% image item.image fill-320x240 %}
  323. <p>{{ item.caption }}</p>
  324. </div>
  325. {% endfor %}
  326. <p><a href="{{ page.get_parent.url }}">Return to blog</a></p>
  327. {% endblock %}
  328. Here we use the ``{% image %}`` tag (which exists in the ``wagtailimages_tags`` library, imported at the top of the template) to insert an ``<img>`` element, with a ``fill-320x240`` parameter to indicate that the image should be resized and cropped to fill a 320x240 rectangle. You can read more about using images in templates in the :doc:`docs <../topics/images>`.
  329. .. figure:: ../_static/images/tutorial/tutorial_6.jpg
  330. :alt: A blog post sample
  331. Since our gallery images are database objects in their own right, we can now query and re-use them independently of the blog post body. Let's define a ``main_image`` method, which returns the image from the first gallery item (or ``None`` if no gallery items exist):
  332. .. code-block:: python
  333. class BlogPage(Page):
  334. date = models.DateField("Post date")
  335. intro = models.CharField(max_length=250)
  336. body = RichTextField(blank=True)
  337. def main_image(self):
  338. gallery_item = self.gallery_images.first()
  339. if gallery_item:
  340. return gallery_item.image
  341. else:
  342. return None
  343. search_fields = Page.search_fields + [
  344. index.SearchField('intro'),
  345. index.SearchField('body'),
  346. ]
  347. content_panels = Page.content_panels + [
  348. FieldPanel('date'),
  349. FieldPanel('intro'),
  350. FieldPanel('body', classname="full"),
  351. InlinePanel('gallery_images', label="Gallery images"),
  352. ]
  353. This method is now available from our templates. Update ``blog_index_page.html`` to include the main image as a thumbnail alongside each post:
  354. .. code-block:: html+django
  355. {% load wagtailcore_tags wagtailimages_tags %}
  356. ...
  357. {% for post in blogpages %}
  358. {% with post=post.specific %}
  359. <h2><a href="{% pageurl post %}">{{ post.title }}</a></h2>
  360. {% with post.main_image as main_image %}
  361. {% if main_image %}{% image main_image fill-160x100 %}{% endif %}
  362. {% endwith %}
  363. <p>{{ post.intro }}</p>
  364. {{ post.body|richtext }}
  365. {% endwith %}
  366. {% endfor %}
  367. Tagging Posts
  368. ~~~~~~~~~~~~~
  369. Let's say we want to let editors "tag" their posts, so that readers can, e.g.,
  370. view all bicycle-related content together. For this, we'll need to invoke
  371. the tagging system bundled with Wagtail, attach it to the ``BlogPage``
  372. model and content panels, and render linked tags on the blog post template.
  373. Of course, we'll need a working tag-specific URL view as well.
  374. First, alter ``models.py`` once more:
  375. .. code-block:: python
  376. from django.db import models
  377. # New imports added for ClusterTaggableManager, TaggedItemBase, MultiFieldPanel
  378. from modelcluster.fields import ParentalKey
  379. from modelcluster.contrib.taggit import ClusterTaggableManager
  380. from taggit.models import TaggedItemBase
  381. from wagtail.core.models import Page, Orderable
  382. from wagtail.core.fields import RichTextField
  383. from wagtail.admin.edit_handlers import FieldPanel, InlinePanel, MultiFieldPanel
  384. from wagtail.images.edit_handlers import ImageChooserPanel
  385. from wagtail.search import index
  386. # ... (Keep the definition of BlogIndexPage)
  387. class BlogPageTag(TaggedItemBase):
  388. content_object = ParentalKey(
  389. 'BlogPage',
  390. related_name='tagged_items',
  391. on_delete=models.CASCADE
  392. )
  393. class BlogPage(Page):
  394. date = models.DateField("Post date")
  395. intro = models.CharField(max_length=250)
  396. body = RichTextField(blank=True)
  397. tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
  398. # ... (Keep the main_image method and search_fields definition)
  399. content_panels = Page.content_panels + [
  400. MultiFieldPanel([
  401. FieldPanel('date'),
  402. FieldPanel('tags'),
  403. ], heading="Blog information"),
  404. FieldPanel('intro'),
  405. FieldPanel('body'),
  406. InlinePanel('gallery_images', label="Gallery images"),
  407. ]
  408. Run ``python manage.py makemigrations`` and ``python manage.py migrate``.
  409. Note the new ``modelcluster`` and ``taggit`` imports, the addition of a new
  410. ``BlogPageTag`` model, and the addition of a ``tags`` field on ``BlogPage``.
  411. We've also taken the opportunity to use a ``MultiFieldPanel`` in ``content_panels``
  412. to group the date and tags fields together for readability.
  413. Edit one of your ``BlogPage`` instances, and you should now be able to tag posts:
  414. .. figure:: ../_static/images/tutorial/tutorial_8.png
  415. :alt: Tagging a post
  416. To render tags on a ``BlogPage``, add this to ``blog_page.html``:
  417. .. code-block:: html+django
  418. {% if page.tags.all.count %}
  419. <div class="tags">
  420. <h3>Tags</h3>
  421. {% for tag in page.tags.all %}
  422. <a href="{% slugurl 'tags' %}?tag={{ tag }}"><button type="button">{{ tag }}</button></a>
  423. {% endfor %}
  424. </div>
  425. {% endif %}
  426. Notice that we're linking to pages here with the builtin ``slugurl``
  427. tag rather than ``pageurl``, which we used earlier. The difference is that ``slugurl`` takes a
  428. Page slug (from the Promote tab) as an argument. ``pageurl`` is more commonly used because it
  429. is unambiguous and avoids extra database lookups. But in the case of this loop, the Page object
  430. isn't readily available, so we fall back on the less-preferred ``slugurl`` tag.
  431. Visiting a blog post with tags should now show a set of linked
  432. buttons at the bottom - one for each tag. However, clicking a button
  433. will get you a 404, since we haven't yet defined a "tags" view. Add to ``models.py``:
  434. .. code-block:: python
  435. class BlogTagIndexPage(Page):
  436. def get_context(self, request):
  437. # Filter by tag
  438. tag = request.GET.get('tag')
  439. blogpages = BlogPage.objects.filter(tags__name=tag)
  440. # Update template context
  441. context = super().get_context(request)
  442. context['blogpages'] = blogpages
  443. return context
  444. Note that this Page-based model defines no fields of its own.
  445. Even without fields, subclassing ``Page`` makes it a part of the
  446. Wagtail ecosystem, so that you can give it a title and URL in the
  447. admin, and so that you can manipulate its contents by returning
  448. a QuerySet from its ``get_context()`` method.
  449. Migrate this in, then create a new ``BlogTagIndexPage`` in the admin.
  450. You'll probably want to create the new page/view as a child of Homepage,
  451. parallel to your Blog index. Give it the slug "tags" on the Promote tab.
  452. Access ``/tags`` and Django will tell you what you probably already knew:
  453. you need to create a template ``blog/blog_tag_index_page.html``:
  454. .. code-block:: html+django
  455. {% extends "base.html" %}
  456. {% load wagtailcore_tags %}
  457. {% block content %}
  458. {% if request.GET.tag|length %}
  459. <h4>Showing pages tagged "{{ request.GET.tag }}"</h4>
  460. {% endif %}
  461. {% for blogpage in blogpages %}
  462. <p>
  463. <strong><a href="{% pageurl blogpage %}">{{ blogpage.title }}</a></strong><br />
  464. <small>Revised: {{ blogpage.latest_revision_created_at }}</small><br />
  465. {% if blogpage.author %}
  466. <p>By {{ blogpage.author.profile }}</p>
  467. {% endif %}
  468. </p>
  469. {% empty %}
  470. No pages found with that tag.
  471. {% endfor %}
  472. {% endblock %}
  473. We're calling the built-in ``latest_revision_created_at`` field on the ``Page``
  474. model - handy to know this is always available.
  475. We haven't yet added an "author" field to our ``BlogPage`` model, nor do we have
  476. a Profile model for authors - we'll leave those as an exercise for the reader.
  477. Clicking the tag button at the bottom of a BlogPost should now render a page
  478. something like this:
  479. .. figure:: ../_static/images/tutorial/tutorial_9.png
  480. :alt: A simple tag view
  481. .. _tutorial_categories:
  482. Categories
  483. ~~~~~~~~~~
  484. Let's add a category system to our blog. Unlike tags, where a page author can bring a tag into existence simply by using it on a page, our categories will be a fixed list, managed by the site owner through a separate area of the admin interface.
  485. First, we define a ``BlogCategory`` model. A category is not a page in its own right, and so we define it as a standard Django ``models.Model`` rather than inheriting from ``Page``. Wagtail introduces the concept of "snippets" for reusable pieces of content that need to be managed through the admin interface, but do not exist as part of the page tree themselves; a model can be registered as a snippet by adding the ``@register_snippet`` decorator. All the field types we've used so far on pages can be used on snippets too - here we'll give each category an icon image as well as a name. Add to ``blog/models.py``:
  486. .. code-block:: python
  487. from wagtail.snippets.models import register_snippet
  488. @register_snippet
  489. class BlogCategory(models.Model):
  490. name = models.CharField(max_length=255)
  491. icon = models.ForeignKey(
  492. 'wagtailimages.Image', null=True, blank=True,
  493. on_delete=models.SET_NULL, related_name='+'
  494. )
  495. panels = [
  496. FieldPanel('name'),
  497. ImageChooserPanel('icon'),
  498. ]
  499. def __str__(self):
  500. return self.name
  501. class Meta:
  502. verbose_name_plural = 'blog categories'
  503. .. note::
  504. Note that we are using ``panels`` rather than ``content_panels`` here - since snippets generally have no need for fields such as slug or publish date, the editing interface for them is not split into separate 'content' / 'promote' / 'settings' tabs as standard, and so there is no need to distinguish between 'content panels' and 'promote panels'.
  505. Migrate this change in, and create a few categories through the Snippets area which now appears in the admin menu.
  506. We can now add categories to the ``BlogPage`` model, as a many-to-many field. The field type we use for this is ``ParentalManyToManyField`` - this is a variant of the standard Django ``ManyToManyField`` which ensures that the chosen objects are correctly stored against the page record in the revision history, in much the same way that ``ParentalKey`` replaces ``ForeignKey`` for one-to-many relations.
  507. .. code-block:: python
  508. # New imports added for forms and ParentalManyToManyField
  509. from django import forms
  510. from django.db import models
  511. from modelcluster.fields import ParentalKey, ParentalManyToManyField
  512. from modelcluster.contrib.taggit import ClusterTaggableManager
  513. from taggit.models import TaggedItemBase
  514. # ...
  515. class BlogPage(Page):
  516. date = models.DateField("Post date")
  517. intro = models.CharField(max_length=250)
  518. body = RichTextField(blank=True)
  519. tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
  520. categories = ParentalManyToManyField('blog.BlogCategory', blank=True)
  521. # ... (Keep the main_image method and search_fields definition)
  522. content_panels = Page.content_panels + [
  523. MultiFieldPanel([
  524. FieldPanel('date'),
  525. FieldPanel('tags'),
  526. FieldPanel('categories', widget=forms.CheckboxSelectMultiple),
  527. ], heading="Blog information"),
  528. FieldPanel('intro'),
  529. FieldPanel('body'),
  530. InlinePanel('gallery_images', label="Gallery images"),
  531. ]
  532. Here we're making use of the ``widget`` keyword argument on the ``FieldPanel`` definition to specify a checkbox-based widget instead of the default multiple select box, as this is often considered more user-friendly.
  533. Finally, we can update the ``blog_page.html`` template to display the categories:
  534. .. code-block:: html+django
  535. <h1>{{ page.title }}</h1>
  536. <p class="meta">{{ page.date }}</p>
  537. {% with categories=page.categories.all %}
  538. {% if categories %}
  539. <h3>Posted in:</h3>
  540. <ul>
  541. {% for category in categories %}
  542. <li style="display: inline">
  543. {% image category.icon fill-32x32 style="vertical-align: middle" %}
  544. {{ category.name }}
  545. </li>
  546. {% endfor %}
  547. </ul>
  548. {% endif %}
  549. {% endwith %}
  550. .. figure:: ../_static/images/tutorial/tutorial_10.jpg
  551. :alt: A blog post with categories
  552. Where next
  553. ----------
  554. - Read the Wagtail :doc:`topics <../topics/index>` and :doc:`reference <../reference/index>` documentation
  555. - Learn how to implement :doc:`StreamField <../topics/streamfield>` for freeform page content
  556. - Browse through the :doc:`advanced topics <../advanced_topics/index>` section and read :doc:`third-party tutorials <../advanced_topics/third_party_tutorials>`