2
0

tutorial.rst 30 KB

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