• Stars
    star
    120
  • Rank 295,983 (Top 6 %)
  • Language
    Python
  • License
    BSD 3-Clause "New...
  • Created over 5 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Previews for headless Wagtail setups

Wagtail Headless Preview

Build status PyPI black pre-commit.ci status

Overview

With Wagtail as the backend, and a separate app for the front-end (for example a single page React app), editors are no longer able to preview their changes. This is because the front-end is no longer within Wagtail's direct control. The preview data therefore needs to be exposed to the front-end app.

This package enables previews for Wagtail pages when used in a headless setup by routing the preview to the specified front-end URL.

Setup

Install using pip:

pip install wagtail-headless-preview

After installing the module, add wagtail_headless_preview to installed apps in your settings file:

# settings.py

INSTALLED_APPS = [
    # ...
    "wagtail_headless_preview",
]

Run migrations:

$ python manage.py migrate

Then configure the preview client URL using the CLIENT_URLS option in the WAGTAIL_HEADLESS_PREVIEW setting.

Configuration

wagtail_headless_preview uses a single settings dictionary:

# settings.py

WAGTAIL_HEADLESS_PREVIEW = {
    "CLIENT_URLS": {},  # defaults to an empty dict. You must at the very least define the default client URL.
    "SERVE_BASE_URL": None,  # can be used for HeadlessServeMixin
    "REDIRECT_ON_PREVIEW": False,  # set to True to redirect to the preview instead of using the Wagtail default mechanism
    "ENFORCE_TRAILING_SLASH": True,  # set to False in order to disable the trailing slash enforcement
}

Single site setup

For single sites, add the front-end URL as the default entry:

WAGTAIL_HEADLESS_PREVIEW = {
    "CLIENT_URLS": {
        "default": "http://localhost:8020",
    }
}

If you have configured your Wagtail Site entry to use the front-end URL, then you can update your configuration to:

WAGTAIL_HEADLESS_PREVIEW = {
    "CLIENT_URLS": {
        "default": "{SITE_ROOT_URL}",
    }
}

The {SITE_ROOT_URL} placeholder is replaced with the root_url property of the Site the preview page belongs to.

Multi-site setup

For a multi-site setup, add each site as a separate entry in the CLIENT_URLS option in the WAGTAIL_HEADLESS_PREVIEW setting:

WAGTAIL_HEADLESS_PREVIEW = {
    "CLIENT_URLS": {
        "default": "https://wagtail.org",  # adjust to match your front-end URL. e.g. locally it may be something like http://localhost:8020
        "cms.wagtail.org": "https://wagtail.org",
        "cms.torchbox.com": "http://torchbox.com",
    },
    # ...
}

Serve URL

To make the editing experience seamles and to avoid server errors due to missing templates, you can use the HeadlessMixin which combines the HeadlessServeMixin and HeadlessPreviewMixin mixins.

HeadlessServeMixin overrides the Wagtail Page.serve method to redirect to the client URL. By default, it uses the hosts defined in CLIENT_URLS. However, you can provide a single URL to rule them all:

# settings.py

WAGTAIL_HEADLESS_PREVIEW = {
    # ...
    "SERVE_BASE_URL": "https://my.headless.site",
}

Enforce trailing slash

By default, wagtail_headless_preview enforces a trailing slash on the client URL. You can disable this behaviour by setting ENFORCE_TRAILING_SLASH to False:

# settings.py
WAGTAIL_HEADLESS_PREVIEW = {
    # ...
    "ENFORCE_TRAILING_SLASH": False
}

Usage

To enable preview as well as wire in the "View live" button in the Wagtail UI, add the HeadlessMixin to your Page class:

from wagtail_headless_preview.models import HeadlessMixin


class MyWonderfulPage(HeadlessMixin, Page):
    pass

If you require more granular control, or if you've modified you Page model's serve method, you can add HeadlessPreviewMixin to your Page class to only handle previews:

from wagtail_headless_preview.models import HeadlessPreviewMixin


class MyWonderfulPage(HeadlessPreviewMixin, Page):
    pass

How will my front-end app display preview content?

This depends on your project, as it will be dictated by the requirements of your front-end app.

The following example uses a Wagtail API endpoint to access previews - your app may opt to access page previews using GraphQL instead.

Example

This example sets up an API endpoint which will return the preview for a page, and then displays that data on a simplified demo front-end app.

  • Add wagtail.api.v2 to the installed apps:
# settings.py

INSTALLED_APPS = [
    # ...
    "wagtail.api.v2",
]
  • create an api.py file in your project directory:
from django.contrib.contenttypes.models import ContentType

from wagtail.api.v2.router import WagtailAPIRouter
from wagtail.api.v2.views import PagesAPIViewSet

from wagtail_headless_preview.models import PagePreview
from rest_framework.response import Response


# Create the router. "wagtailapi" is the URL namespace
api_router = WagtailAPIRouter("wagtailapi")


class PagePreviewAPIViewSet(PagesAPIViewSet):
    known_query_parameters = PagesAPIViewSet.known_query_parameters.union(
        ["content_type", "token"]
    )

    def listing_view(self, request):
        page = self.get_object()
        serializer = self.get_serializer(page)
        return Response(serializer.data)

    def detail_view(self, request, pk):
        page = self.get_object()
        serializer = self.get_serializer(page)
        return Response(serializer.data)

    def get_object(self):
        app_label, model = self.request.GET["content_type"].split(".")
        content_type = ContentType.objects.get(app_label=app_label, model=model)

        page_preview = PagePreview.objects.get(
            content_type=content_type, token=self.request.GET["token"]
        )
        page = page_preview.as_page()
        if not page.pk:
            # fake primary key to stop API URL routing from complaining
            page.pk = 0

        return page


api_router.register_endpoint("page_preview", PagePreviewAPIViewSet)
  • Register the API URLs so Django can route requests into the API:
# urls.py

from .api import api_router

urlpatterns = [
    # ...
    path("api/v2/", api_router.urls),
    # ...
    # Ensure that the api_router line appears above the default Wagtail page serving route
    path("", include(wagtail_urls)),
]

For further information about configuring the wagtail API, refer to the Wagtail API v2 Configuration Guide

  • Next, add a client/index.html file in your project root. This will query the API to display our preview:
<!DOCTYPE html>
<html>
<head>
    <script>
        function go() {
            var querystring = window.location.search.replace(/^\?/, '');
            var params = {};
            querystring.replace(/([^=&]+)=([^&]*)/g, function(m, key, value) {
                params[decodeURIComponent(key)] = decodeURIComponent(value);
            });

            var apiUrl = 'http://localhost:8000/api/v2/page_preview/1/?content_type=' + encodeURIComponent(params['content_type']) + '&token=' + encodeURIComponent(params['token']) + '&format=json';
            fetch(apiUrl).then(function(response) {
                response.text().then(function(text) {
                    document.body.innerText = text;
                });
            });
        }
    </script>
</head>
<body onload="go()"></body>
</html>
  • Install django-cors-headers: pip install django-cors-headers
  • Add CORS config to your settings file to allow the front-end to access the API
# settings.py
CORS_ORIGIN_ALLOW_ALL = True
CORS_URLS_REGEX = r"^/api/v2/"

and follow the rest of the setup instructions for django-cors-headers.

  • Start up your site as normal: python manage.py runserver 0:8000
  • Serve the front-end client/index.html at http://localhost:8020/
    • this can be done by running python3 -m http.server 8020 from inside the client directory
  • From the wagtail admin interface, edit (or create) and preview a page that uses HeadlessPreviewMixin

The preview page should now show you the API response for the preview! 🎉

This is where a real front-end would take over and display the preview as it would be seen on the live site.

Contributing

All contributions are welcome!

Note that this project uses pre-commit. To set up locally:

# if you don't have it yet
$ pip install pre-commit
# go to the project directory
$ cd wagtail-headless-preview
# initialize pre-commit
$ pre-commit install

# Optional, run all checks once for this, then the checks will run only on the changed files
$ pre-commit run --all-files

How to run tests

Now you can run tests as shown below:

tox -p

or, you can run them for a specific environment tox -e py39-django3.2-wagtail4.1 or specific test tox -e py310-django3.2-wagtail4.1 wagtail_headless_preview.tests.test_frontend.TestFrontendViews.test_redirect_on_preview

Credits

  • Matthew Westcott (@gasman), initial proof of concept
  • Karl Hobley (@kaedroho), PoC improvements

More Repositories

1

django-recaptcha

New maintainers 🚧 --- Django reCAPTCHA form field/widget integration app.
Python
929
star
2

django-pattern-library

UI pattern libraries for Django templates
Python
368
star
3

django-libsass

A django-compressor filter to compile SASS files using libsass
Python
265
star
4

vagrant-django-template

Skeleton project for a Django app running under Vagrant
Python
240
star
5

wagtailmedia

A Wagtail module for managing video and audio files within the admin
Python
233
star
6

wagtail-markdown

Markdown support for Wagtail
Python
198
star
7

wagtail-grapple

A Wagtail app that makes building GraphQL endpoints a breeze!
Python
154
star
8

wagtail-torchbox

Wagtail build of Torchbox.com
Python
124
star
9

wagtail-experiments

A/B testing for Wagtail
Python
105
star
10

vagrant-django-base

Vagrant configuration for a base box for Django development
Shell
90
star
11

storybook-django

Develop Django UI components in isolation, with Storybook
JavaScript
83
star
12

cookiecutter-wagtail

Python
54
star
13

k8s-hostpath-provisioner

Network storage provisioner for Kubernetes
Go
52
star
14

kdtool

Kubernetes deployment utility
Python
45
star
15

kube-ldap-authn

Kubernetes LDAP authentication service
Python
42
star
16

wagtail-wordpress-import

A package for Wagtail CMS to import WordPress blog content from an XML file into Wagtail
Python
40
star
17

wagtail-storages

Use AWS S3 with private documents in Wagtail
Python
40
star
18

design-in-browser-bootstrap

An aid to quickly starting Design In the Browser
JavaScript
34
star
19

wagtail-import-export

UNMAINTAINED. Try wagtail-transfer, the evolution of this package: https://github.com/wagtail/wagtail-transfer/
Python
32
star
20

wagtail-content-import

A module for importing page content into Wagtail from third-party sources. Docs:
Python
32
star
21

rustface-py

Python library for detecting faces in images.
Rust
31
star
22

wagtailquickcreate

Wagtail Quick Create offers shortcut links to create objects from models specified in your settings file.
Python
25
star
23

wagtailguide

An app for adding a CMS guide to your Wagtail CMS
Python
23
star
24

k8s-ts-ingress

Kubernetes Ingress controller as a Traffic Server plugin
C
22
star
25

wagtailsurveys

Python
21
star
26

vagrant-thumbor-base

Vagrant box providing a thumbor service over HTTP
Shell
20
star
27

wagtail-footnotes

Python
20
star
28

wagtail-template

A Django template for starting new Wagtail projects with Vagrant. NO LONGER MAINTANED
Python
19
star
29

buckup

Creating S3 buckets for your site with ease.
Python
18
star
30

wagtail-ab-testing

A/B testing for Wagtail
Python
17
star
31

torchbox-frontend

JavaScript
16
star
32

wagtail-appengine-demo

The simplest possible Wagtail site on Google Cloud
CSS
15
star
33

django-basic-auth-ip-whitelist

Hide your Django site behind basic authentication with IP whitelisting support
Python
14
star
34

verdant-rca

Python
13
star
35

docker-php

Docker PHP Images based on official PHP
Shell
12
star
36

longform

A plugin for longform content in Wagtail
CSS
12
star
37

wagtail-purge

A simple Wagtail admin UI for removing individual pages from your CDN's cache
Python
10
star
38

wagtail-webstories

AMP web story support for Wagtail
Python
9
star
39

rca-wagtail-2019

Python
8
star
40

stylelint-config-torchbox

Shareable stylelint config for CSS and SCSS, following Torchbox’s code style.
JavaScript
7
star
41

cloudflare-recipes

Cloudflare service worker recipes
JavaScript
7
star
42

trafficserver-ingress-controller

Apache Traffic Server ingress controller for Kubernetes
Perl
7
star
43

tbxforms

A Torchbox-flavoured template pack for django-crispy-forms, adapted from crispy-forms-gds.
HTML
6
star
44

wagtailapi

A module for adding a read only, JSON based web API to your Wagtail site (NO LONGER MAINTAINED! Use Wagtails contrib.wagtailapi module instead)
Python
6
star
45

webstories

Parser for AMP web stories
Python
6
star
46

wagtail-makeup

Wagtail plugin to replace all your broken local images with unsplash ones
Python
6
star
47

samaritans-patterns

HTML
5
star
48

wagtail-bookmarklet

Gives Wagtail editors an 'edit this page' bookmarklet, for scenarios where the user bar isn't available
Python
5
star
49

django-registration

Tweaked Django >=1.6-compatible version of django-registration
Python
5
star
50

careers

Torchbox careers site
TypeScript
4
star
51

ample

Cross-browser audio playback library, with HTML5 and Flash backends
JavaScript
4
star
52

wagtail-periodic-review

A Wagtail package for periodic page content reviews
Python
4
star
53

nhs-organisations

Python
3
star
54

wagtail-jotform

A plugin for using jotforms in wagtail
Python
3
star
55

wagtail-bynder

Wagtail + Bynder Digital Asset Management System integration
Python
3
star
56

wagtailapidemo

Wagtaildemo with API enabled
Python
3
star
57

eslint-config-torchbox

Shareable ESLint config following Torchbox’s code style
JavaScript
3
star
58

wagtail-mongodb

Python
3
star
59

christmas-video-2017

CSS
2
star
60

dit_directory_cms_poc

Proof-of-concepts for potential improvements to uktrade/directory-cms
Python
2
star
61

wagtail-related

Python
2
star
62

resourcespace_plugin-api_markasused

API plugin for resourcespace that updates a resourcespace entry
PHP
2
star
63

wagtail-azure-cdn

Use Azure CDN with Wagtail CMS.
Python
2
star
64

heroku-cloudflare-app-domain

Create branded herokuapp.com domains through Cloudflare
Python
2
star
65

demo.wagtail.io

Configuration for demo.wagtail.io
Python
2
star
66

christmaschorus

the 2011 musical christmas card
JavaScript
2
star
67

ngxpurged

nginx cache purge daemon
Python
2
star
68

django-tagging

Fork via PyPI v0.3.4 to maintain Django compatibility. Unmaintained for Django >= 1.10
Python
2
star
69

torchbox.com

Torchbox website 2024 incarnation
Python
2
star
70

resourcespace_plugin-api_resource

API plugin for resourcespace that fetches a resource metadata or a resource file in stream
PHP
2
star
71

docker-rsync

Trivial Docker image containing Alpine Linux with rsync installed
Makefile
1
star
72

heroku-restarter

Restarts Heroku applications based on timeout alerts in Papertrail
Python
1
star
73

django-piston

Fork of the popular REST API mini-framework
Python
1
star
74

tate-cms

Tate CMS project’s sprint notes
1
star
75

kube-registry-proxy

Shell
1
star
76

docker-trafficserver

1
star
77

healtheintent-api-python

Python
1
star
78

raxtool

Rackspace Cloud management tool
Python
1
star
79

ceph-rbd-provisioner

1
star
80

django-importo

A developer-friendly framework for importing data into Django apps
Python
1
star
81

wagtail_picture_proposal

Code snippets for an experimental picture tag for Wagtail. Not intended for reuse
Python
1
star
82

nlbq

Natural language interface to BigQuery
Python
1
star
83

nuffield-nhs-timeline

Nuffield NHS Timeline
HTML
1
star