pages.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. ===========
  2. Page models
  3. ===========
  4. Each page type (a.k.a. content type) in Wagtail is represented by a Django model. All page models must inherit from the :class:`wagtail.core.models.Page` class.
  5. As all page types are Django models, you can use any field type that Django provides. See :doc:`Model field reference <django:ref/models/fields>` for a complete list of field types you can use. Wagtail also provides :class:`~wagtail.core.fields.RichTextField` which provides a WYSIWYG editor for editing rich-text content.
  6. .. topic:: Django models
  7. If you're not yet familiar with Django models, have a quick look at the following links to get you started:
  8. * :ref:`Creating models <django:creating-models>`
  9. * :doc:`Model syntax <django:topics/db/models>`
  10. An example Wagtail page model
  11. =============================
  12. This example represents a typical blog post:
  13. .. code-block:: python
  14. from django.db import models
  15. from modelcluster.fields import ParentalKey
  16. from wagtail.core.models import Page, Orderable
  17. from wagtail.core.fields import RichTextField
  18. from wagtail.admin.edit_handlers import FieldPanel, MultiFieldPanel, InlinePanel
  19. from wagtail.images.edit_handlers import ImageChooserPanel
  20. from wagtail.search import index
  21. class BlogPage(Page):
  22. # Database fields
  23. body = RichTextField()
  24. date = models.DateField("Post date")
  25. feed_image = models.ForeignKey(
  26. 'wagtailimages.Image',
  27. null=True,
  28. blank=True,
  29. on_delete=models.SET_NULL,
  30. related_name='+'
  31. )
  32. # Search index configuration
  33. search_fields = Page.search_fields + [
  34. index.SearchField('body'),
  35. index.FilterField('date'),
  36. ]
  37. # Editor panels configuration
  38. content_panels = Page.content_panels + [
  39. FieldPanel('date'),
  40. FieldPanel('body', classname="full"),
  41. InlinePanel('related_links', label="Related links"),
  42. ]
  43. promote_panels = [
  44. MultiFieldPanel(Page.promote_panels, "Common page configuration"),
  45. ImageChooserPanel('feed_image'),
  46. ]
  47. # Parent page / subpage type rules
  48. parent_page_types = ['blog.BlogIndex']
  49. subpage_types = []
  50. class BlogPageRelatedLink(Orderable):
  51. page = ParentalKey(BlogPage, on_delete=models.CASCADE, related_name='related_links')
  52. name = models.CharField(max_length=255)
  53. url = models.URLField()
  54. panels = [
  55. FieldPanel('name'),
  56. FieldPanel('url'),
  57. ]
  58. .. important::
  59. Ensure that none of your field names are the same as your class names. This will cause errors due to the way Django handles relations (`read more <https://github.com/wagtail/wagtail/issues/503>`_). In our examples we have avoided this by appending "Page" to each model name.
  60. Writing page models
  61. ===================
  62. Here we'll describe each section of the above example to help you create your own page models.
  63. Database fields
  64. ---------------
  65. Each Wagtail page type is a Django model, represented in the database as a separate table.
  66. Each page type can have its own set of fields. For example, a news article may have body text and a published date, whereas an event page may need separate fields for venue and start/finish times.
  67. In Wagtail, you can use any Django field class. Most field classes provided by third party apps should work as well.
  68. Wagtail also provides a couple of field classes of its own:
  69. - ``RichTextField`` - For rich text content
  70. - ``StreamField`` - A block-based content field (see: :doc:`/topics/streamfield`)
  71. For tagging, Wagtail fully supports `django-taggit <https://django-taggit.readthedocs.org/en/latest/>`_ so we recommend using that.
  72. Search
  73. ------
  74. The ``search_fields`` attribute defines which fields are added to the search index and how they are indexed.
  75. This should be a list of ``SearchField`` and ``FilterField`` objects. ``SearchField`` adds a field for full-text search. ``FilterField`` adds a field for filtering the results. A field can be indexed with both ``SearchField`` and ``FilterField`` at the same time (but only one instance of each).
  76. In the above example, we've indexed ``body`` for full-text search and ``date`` for filtering.
  77. The arguments that these field types accept are documented in :ref:`wagtailsearch_indexing_fields`.
  78. Editor panels
  79. -------------
  80. There are a few attributes for defining how the page's fields will be arranged in the page editor interface:
  81. - ``content_panels`` - For content, such as main body text
  82. - ``promote_panels`` - For metadata, such as tags, thumbnail image and SEO title
  83. - ``settings_panels`` - For settings, such as publish date
  84. Each of these attributes is set to a list of ``EditHandler`` objects, which defines which fields appear on which tabs and how they are structured on each tab.
  85. Here's a summary of the ``EditHandler`` classes that Wagtail provides out of the box. See :doc:`/reference/pages/panels` for full descriptions.
  86. **Basic**
  87. These allow editing of model fields. The ``FieldPanel`` class will choose the correct widget based on the type of the field, though ``StreamField`` fields need to use a specialised panel class.
  88. - :class:`~wagtail.admin.edit_handlers.FieldPanel`
  89. - :class:`~wagtail.admin.edit_handlers.StreamFieldPanel`
  90. **Structural**
  91. These are used for structuring fields in the interface.
  92. - :class:`~wagtail.admin.edit_handlers.MultiFieldPanel` - For grouping similar fields together
  93. - :class:`~wagtail.admin.edit_handlers.InlinePanel` - For inlining child models
  94. - :class:`~wagtail.admin.edit_handlers.FieldRowPanel` - For organising multiple fields into a single row
  95. **Chooser**
  96. ``ForeignKey`` fields to certain models can use one of the below ``ChooserPanel`` classes. These add a nice modal chooser interface, and the image/document choosers also allow uploading new files without leaving the page editor.
  97. - :class:`~wagtail.admin.edit_handlers.PageChooserPanel`
  98. - :class:`~wagtail.images.edit_handlers.ImageChooserPanel`
  99. - :class:`~wagtail.documents.edit_handlers.DocumentChooserPanel`
  100. - :class:`~wagtail.snippets.edit_handlers.SnippetChooserPanel`
  101. .. note::
  102. In order to use one of these choosers, the model being linked to must either be a page, image, document or snippet.
  103. To link to any other model type, you should use ``FieldPanel``, which will create a dropdown box.
  104. Customising the page editor interface
  105. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  106. The page editor can be customised further. See :doc:`/advanced_topics/customisation/page_editing_interface`.
  107. .. _page_type_business_rules:
  108. Parent page / subpage type rules
  109. --------------------------------
  110. These two attributes allow you to control where page types may be used in your site. It allows you to define rules like "blog entries may only be created under a blog index".
  111. Both take a list of model classes or model names. Model names are of the format ``app_label.ModelName``. If the ``app_label`` is omitted, the same app is assumed.
  112. - ``parent_page_types`` limits which page types this type can be created under
  113. - ``subpage_types`` limits which page types can be created under this type
  114. By default, any page type can be created under any page type and it is not necessary to set these attributes if that's the desired behaviour.
  115. Setting ``parent_page_types`` to an empty list is a good way of preventing a particular page type from being created in the editor interface.
  116. .. _page_urls:
  117. Page URLs
  118. ---------
  119. The most common method of retrieving page URLs is by using the ``{% pageurl %}`` template tag. Since it's called from a template, ``pageurl`` automatically includes the optimizations mentioned below. For more information, see :ref:`pageurl_tag`.
  120. Page models also include several low-level methods for overriding or accessing page URLs.
  121. Customising URL patterns for a page model
  122. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  123. The ``Page.get_url_parts(request)`` method will not typically be called directly, but may be overridden to define custom URL routing for a given page model. It should return a tuple of ``(site_id, root_url, page_path)``, which are used by ``get_url`` and ``get_full_url`` (see below) to construct the given type of page URL.
  124. When overriding ``get_url_parts()``, you should accept ``*args, **kwargs``:
  125. .. code-block:: python
  126. def get_url_parts(self, *args, **kwargs):
  127. and pass those through at the point where you are calling ``get_url_parts`` on ``super`` (if applicable), e.g.:
  128. .. code-block:: python
  129. super().get_url_parts(*args, **kwargs)
  130. While you could pass only the ``request`` keyword argument, passing all arguments as-is ensures compatibility with any
  131. future changes to these method signatures.
  132. For more information, please see :meth:`wagtail.core.models.Page.get_url_parts`.
  133. Obtaining URLs for page instances
  134. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  135. The ``Page.get_url(request)`` method can be called whenever a page URL is needed. It defaults to returning local URLs (not including the protocol or domain) if it determines that the page is on the current site (via the hostname in ``request``); otherwise, a full URL including the protocol and domain is returned. Whenever possible, the optional ``request`` argument should be included to enable per-request caching of site-level URL information and facilitate the generation of local URLs.
  136. A common use case for ``get_url(request)`` is in any custom template tag your project may include for generating navigation menus. When writing such a custom template tag, ensure that it includes ``takes_context=True`` and use ``context.get('request')`` to safely pass the
  137. request or ``None`` if no request exists in the context.
  138. For more information, please see :meth:`wagtail.core.models.Page.get_url`.
  139. In the event a full URL (including the protocol and domain) is needed, ``Page.get_full_url(request)`` can be used instead. Whenever possible, the optional ``request`` argument should be included to enable per-request caching of site-level URL information. For more information, please see :meth:`wagtail.core.models.Page.get_full_url`.
  140. Template rendering
  141. ==================
  142. Each page model can be given an HTML template which is rendered when a user browses to a page on the site frontend. This is the simplest and most common way to get Wagtail content to end users (but not the only way).
  143. Adding a template for a page model
  144. ----------------------------------
  145. Wagtail automatically chooses a name for the template based on the app label and model class name.
  146. Format: ``<app_label>/<model_name (snake cased)>.html``
  147. For example, the template for the above blog page will be: ``blog/blog_page.html``
  148. You just need to create a template in a location where it can be accessed with this name.
  149. Template context
  150. ----------------
  151. Wagtail renders templates with the ``page`` variable bound to the page instance being rendered. Use this to access the content of the page. For example, to get the title of the current page, use ``{{ page.title }}``. All variables provided by :ref:`context processors <subclassing-context-requestcontext>` are also available.
  152. Customising template context
  153. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  154. All pages have a ``get_context`` method that is called whenever the template is rendered and returns a dictionary of variables to bind into the template.
  155. To add more variables to the template context, you can override this method:
  156. .. code-block:: python
  157. class BlogIndexPage(Page):
  158. ...
  159. def get_context(self, request):
  160. context = super().get_context(request)
  161. # Add extra variables and return the updated context
  162. context['blog_entries'] = BlogPage.objects.child_of(self).live()
  163. return context
  164. The variables can then be used in the template:
  165. .. code-block:: HTML+Django
  166. {{ page.title }}
  167. {% for entry in blog_entries %}
  168. {{ entry.title }}
  169. {% endfor %}
  170. Changing the template
  171. ---------------------
  172. Set the ``template`` attribute on the class to use a different template file:
  173. .. code-block:: python
  174. class BlogPage(Page):
  175. ...
  176. template = 'other_template.html'
  177. Dynamically choosing the template
  178. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  179. The template can be changed on a per-instance basis by defining a ``get_template`` method on the page class. This method is called every time the page is rendered:
  180. .. code-block:: python
  181. class BlogPage(Page):
  182. ...
  183. use_other_template = models.BooleanField()
  184. def get_template(self, request):
  185. if self.use_other_template:
  186. return 'blog/other_blog_page.html'
  187. return 'blog/blog_page.html'
  188. In this example, pages that have the ``use_other_template`` boolean field set will use the ``blog/other_blog_page.html`` template. All other pages will use the default ``blog/blog_page.html``.
  189. Ajax Templates
  190. ~~~~~~~~~~~~~~
  191. If you want to add AJAX functionality to a page, such as a paginated listing that updates in-place on the page rather than triggering a full page reload, you can set the ``ajax_template`` attribute to specify an alternative template to be used when the page is requested via an AJAX call (as indicated by the ``X-Requested-With: XMLHttpRequest`` HTTP header):
  192. .. code-block:: python
  193. class BlogPage(Page):
  194. ...
  195. ajax_template = 'other_template_fragment.html'
  196. template = 'other_template.html'
  197. More control over page rendering
  198. --------------------------------
  199. All page classes have a ``serve()`` method that internally calls the ``get_context`` and ``get_template`` methods and renders the template. This method is similar to a Django view function, taking a Django ``Request`` object and returning a Django ``Response`` object.
  200. This method can also be overridden for complete control over page rendering.
  201. For example, here's a way to make a page respond with a JSON representation of itself:
  202. .. code-block:: python
  203. from django.http import JsonResponse
  204. class BlogPage(Page):
  205. ...
  206. def serve(self, request):
  207. return JsonResponse({
  208. 'title': self.title,
  209. 'body': self.body,
  210. 'date': self.date,
  211. # Resizes the image to 300px width and gets a URL to it
  212. 'feed_image': self.feed_image.get_rendition('width-300').url,
  213. })
  214. Inline models
  215. =============
  216. Wagtail can nest the content of other models within the page. This is useful for creating repeated fields, such as related links or items to display in a carousel. Inline model content is also versioned with the rest of the page content.
  217. Each inline model requires the following:
  218. - It must inherit from :class:`wagtail.core.models.Orderable`
  219. - It must have a ``ParentalKey`` to the parent model
  220. .. note:: django-modelcluster and ParentalKey
  221. The model inlining feature is provided by `django-modelcluster <https://github.com/torchbox/django-modelcluster>`_ and the ``ParentalKey`` field type must be imported from there:
  222. .. code-block:: python
  223. from modelcluster.fields import ParentalKey
  224. ``ParentalKey`` is a subclass of Django's ``ForeignKey``, and takes the same arguments.
  225. For example, the following inline model can be used to add related links (a list of name, url pairs) to the ``BlogPage`` model:
  226. .. code-block:: python
  227. from django.db import models
  228. from modelcluster.fields import ParentalKey
  229. from wagtail.core.models import Orderable
  230. class BlogPageRelatedLink(Orderable):
  231. page = ParentalKey(BlogPage, on_delete=models.CASCADE, related_name='related_links')
  232. name = models.CharField(max_length=255)
  233. url = models.URLField()
  234. panels = [
  235. FieldPanel('name'),
  236. FieldPanel('url'),
  237. ]
  238. To add this to the admin interface, use the :class:`~wagtail.admin.edit_handlers.InlinePanel` edit panel class:
  239. .. code-block:: python
  240. content_panels = [
  241. ...
  242. InlinePanel('related_links', label="Related links"),
  243. ]
  244. The first argument must match the value of the ``related_name`` attribute of the ``ParentalKey``.
  245. Working with pages
  246. ==================
  247. Wagtail uses Django's :ref:`multi-table inheritance <django:multi-table-inheritance>` feature to allow multiple page models to be used in the same tree.
  248. Each page is added to both Wagtail's builtin :class:`~wagtail.core.models.Page` model as well as its user-defined model (such as the ``BlogPage`` model created earlier).
  249. Pages can exist in Python code in two forms, an instance of ``Page`` or an instance of the page model.
  250. When working with multiple page types together, you will typically use instances of Wagtail's :class:`~wagtail.core.models.Page` model, which don't give you access to any fields specific to their type.
  251. .. code-block:: python
  252. # Get all pages in the database
  253. >>> from wagtail.core.models import Page
  254. >>> Page.objects.all()
  255. [<Page: Homepage>, <Page: About us>, <Page: Blog>, <Page: A Blog post>, <Page: Another Blog post>]
  256. When working with a single page type, you can work with instances of the user-defined model. These give access to all the fields available in ``Page``, along with any user-defined fields for that type.
  257. .. code-block:: python
  258. # Get all blog entries in the database
  259. >>> BlogPage.objects.all()
  260. [<BlogPage: A Blog post>, <BlogPage: Another Blog post>]
  261. You can convert a ``Page`` object to its more specific user-defined equivalent using the ``.specific`` property. This may cause an additional database lookup.
  262. .. code-block:: python
  263. >>> page = Page.objects.get(title="A Blog post")
  264. >>> page
  265. <Page: A Blog post>
  266. # Note: the blog post is an instance of Page so we cannot access body, date or feed_image
  267. >>> page.specific
  268. <BlogPage: A Blog post>
  269. Tips
  270. ====
  271. Friendly model names
  272. --------------------
  273. You can make your model names more friendly to users of Wagtail by using Django's internal ``Meta`` class with a ``verbose_name``, e.g.:
  274. .. code-block:: python
  275. class HomePage(Page):
  276. ...
  277. class Meta:
  278. verbose_name = "homepage"
  279. When users are given a choice of pages to create, the list of page types is generated by splitting your model names on each of their capital letters. Thus a ``HomePage`` model would be named "Home Page" which is a little clumsy. Defining ``verbose_name`` as in the example above would change this to read "Homepage", which is slightly more conventional.
  280. Page QuerySet ordering
  281. ----------------------
  282. ``Page``-derived models *cannot* be given a default ordering by using the standard Django approach of adding an ``ordering`` attribute to the internal ``Meta`` class.
  283. .. code-block:: python
  284. class NewsItemPage(Page):
  285. publication_date = models.DateField()
  286. ...
  287. class Meta:
  288. ordering = ('-publication_date', ) # will not work
  289. This is because ``Page`` enforces ordering QuerySets by path. Instead, you must apply the ordering explicitly when constructing a QuerySet:
  290. .. code-block:: python
  291. news_items = NewsItemPage.objects.live().order_by('-publication_date')
  292. .. _custom_page_managers:
  293. Custom Page managers
  294. --------------------
  295. You can add a custom ``Manager`` to your ``Page`` class. Any custom Managers should inherit from :class:`wagtail.core.models.PageManager`:
  296. .. code-block:: python
  297. from django.db import models
  298. from wagtail.core.models import Page, PageManager
  299. class EventPageManager(PageManager):
  300. """ Custom manager for Event pages """
  301. class EventPage(Page):
  302. start_date = models.DateField()
  303. objects = EventPageManager()
  304. Alternately, if you only need to add extra ``QuerySet`` methods, you can inherit from :class:`wagtail.core.models.PageQuerySet`, and call :func:`~django.db.models.managers.Manager.from_queryset` to build a custom ``Manager``:
  305. .. code-block:: python
  306. from django.db import models
  307. from django.utils import timezone
  308. from wagtail.core.models import Page, PageManager, PageQuerySet
  309. class EventPageQuerySet(PageQuerySet):
  310. def future(self):
  311. today = timezone.localtime(timezone.now()).date()
  312. return self.filter(start_date__gte=today)
  313. EventPageManager = PageManager.from_queryset(EventPageQuerySet)
  314. class EventPage(Page):
  315. start_date = models.DateField()
  316. objects = EventPageManager()