7

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

Adam Hopkins
  • 6,837
  • 6
  • 32
  • 52

1 Answers1

12

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.

jhrr
  • 1,624
  • 14
  • 22
404
  • 370
  • 3
  • 8
  • Awesome, thanks KS for the answer. Now that I know it's acceptable, (when I'm back in front of a computer) I'll post my code that's not far off from yours. It generates the black bar fine, but there is a JS error when you click a block. Maybe someone can help. It's a pretty vanilla installation, and they work fine in other places so it's a bit puzzling. – Adam Hopkins May 06 '16 at 04:14
  • 1
    FWIW I had a JS error too in a snippet model with stream fields; the fix is to define `panels`. – merwok Jan 15 '19 at 17:21