Wagtail Factories

4.4.0 · active · verified Thu Apr 09

Wagtail Factories provides factory_boy classes tailored for generating Wagtail-specific objects like Pages, Images, Documents, and StreamFields, making it easier to create test data or seed development environments. The library is currently at version 4.4.0 and maintains an active release cadence, frequently updating to support new Wagtail versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a Wagtail page model with a StreamField and then create corresponding `wagtail-factories` for both the page and its StreamField blocks. It uses `StreamFieldFactory` to populate StreamField content and shows how to define factories for specific block types like `CharBlock`. The example highlights the use of `factory.Faker` for realistic data and `factory.Sequence` for unique titles, and notes that execution requires a Django/Wagtail environment.

import factory
from django.db import models
from wagtail.models import Page
from wagtail.fields import RichTextField, StreamField
from wagtail import blocks
from wagtail_factories import PageFactory, StreamFieldFactory
from wagtail_factories.blocks import CharBlockFactory

# Define a simple Wagtail Page model
class MyPage(Page):
    body = RichTextField(blank=True)
    content = StreamField([
        ('heading', blocks.CharBlock(form_classname='full title')),
        ('paragraph', blocks.RichTextBlock()),
    ], use_json_field=True, blank=True)

    content_panels = Page.content_panels # Simplified for example

# Define factories for the model and its StreamField blocks
class HeadingBlockFactory(CharBlockFactory):
    class Meta:
        model = blocks.CharBlock # For CharBlockFactory itself

class MyPageFactory(PageFactory):
    class Meta:
        model = MyPage

    title = factory.Sequence(lambda n: f'Test Page {n}')
    body = factory.Faker('text')
    content = StreamFieldFactory({
        'heading': HeadingBlockFactory,
        'paragraph': StreamFieldFactory._do_nothing, # For simple blocks or when default behavior is fine
    })

# Example usage (requires Django environment setup)
# To run this code, you'd typically need a Django project configured with Wagtail.
# For testing purposes, you might use Django's test client or a custom setup.
if __name__ == '__main__':
    print("This quickstart demonstrates factory definition. To create instances, run within a configured Django/Wagtail project.")
    print("Example: `page = MyPageFactory()` would create a page in your database.")
    # Example of creating a page (would run within a Django test or shell):
    # from django.test import TestCase
    # class MyTest(TestCase):
    #    def test_page_creation(self):
    #        page = MyPageFactory()
    #        self.assertIsNotNone(page.pk)
    #        print(f"Created page: {page.title}")
    #        print(f"StreamField content keys: {[b.block_type for b in page.content]}")

view raw JSON →