pythondjangowagtailwagtail-streamfieldwagtail-snippet

Use of StreamField in Snippets on Wagtail


I am trying to build some structured snippets on my Wagtail site. I looked through the documentation, but saw nothing on this point (forgive me if I missed it).

Is it possible to use StreamField inside of a Snippet? Or, only on Pages


Solution

  • Yes, you can definitely add a Streamfield to a snippet. It works the same as if you use it on a Wagtail Page subclass. Here's an example of it's use:

    from wagtail.core.fields import StreamField
    from wagtail.wagtailsnippets.models import register_snippet
    from wagtail.wagtailadmin.edit_handlers import StreamFieldPanel
    
    @register_snippet
    class Contact(models.Model):
        contact_info = StreamField([
            ('email', MyBlocks.ContactEmail()),
            ('phone', MyBlocks.ContactPhone()),
            ('address', MyBlocks.ContactAddress()),
        ])
    
        panels = [StreamFieldPanel('contact_info')]
    

    Extra stuff you didn't ask for: Streamfield is a Django model field, so it works the same on any model you define it on. Actually, the Streamfield just saves as a JSON string. The only thing that makes it different are the blocks. Blocks that are defined in that first parameter of the Streamfield are really just defining the available options that the Streamfield can use to generate content. The blocks themselves have no bearing on the SQL for CRUD operations, they're only used for manipulating the data saved for the Streamfield.

    Hope that helps.