Creating custom rules

Rules consist of two important elements, the model fields and the test_user function. They should inherit the AbstractBaseRule class from wagtail_personalisation.rules.

A simple example of a rule could look something like this:

class UserIsLoggedInRule(AbstractBaseRule):
    """User is logged in rule to segment users based on their authentication

    Matches when the user is authenticated.

    icon = 'fa-user'

    is_logged_in = models.BooleanField(default=False)

    panels = [

    class Meta:
        verbose_name = _('Logged in Rule')

    def test_user(self, request=None):
        return request.user.is_authenticated() == self.is_logged_in

    def description(self):
        return {
            'title': _('These visitors are'),
            'value': _('Logged in') if self.is_logged_in else _('Not logged in'),

As you can see, the only real requirement is the test_user function that will either return True or False based on the model fields and optionally the request object.

That’s it!