Search code examples
wagtailwagtail-streamfield

Is there any way to add a custom unique identifier to a wagtail block


I am looking to create a streamfield of items with each item having a custom id. I have created an 'ItemBlock' and added a 'unique_identifier' attribute which is populated using uuid4. The issue is that each item has the same uuid. Is there a way to generate a different uuid for each ItemBlock?

class ItemBlock(blocks.StructBlock):
        
    unique_identifier = blocks.CharBlock(default=uuid.uuid4())
    item_name = blocks.CharBlock()
    body = blocks.RichTextBlock()


class CategoryBlock(blocks.StructBlock):
    title = blocks.CharBlock()

class ListPage(Page):
    subtitle = models.CharField(max_length=50)
    checklist = StreamField([('category', CategoryBlock()), ('checklist_item', ItemBlock())])

    
    content_panels = Page.content_panels + [
        FieldPanel('subtitle'),
        StreamFieldPanel('checklist'),
    ]

Solution

  • Wagtail blocks already have UUIDs:

    https://github.com/wagtail/wagtail/blob/master/wagtail/core/blocks/stream_block.py#L452

    You can access them in templates with your_block.id.

    Does this help you?