Skip to content

Allow Block.preview_value and default to be callables for dynamic previews #13196

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

Tombow1
Copy link
Contributor

@Tombow1 Tombow1 commented Jul 2, 2025

Description

This PR implements #13094, proposed by @laymonage.

It adds support for specifying Meta.preview_value and Meta.default as callables (with no arguments), following the convention used by Django model field defaults. This allows for dynamic values (e.g. database lookups, timestamps) without requiring subclassing or eager evaluation.

This also aligns with some of the use cases discussed in #7992.

Demo of the use case mentioned by #7992.

With the demo block code below, we can dynamically generate the datetime without overriding get_preview_value():

class BlockQuote(StructBlock):
    text = TextBlock()
    attribute_name = CharBlock(blank=True, required=False, label="e.g. Mary Berry")

    class Meta:
        icon = "openquote"
        template = "blocks/blockquote.html"
        preview_value = staticmethod(lambda: {
            "text": f"This preview was generated at {datetime.now().strftime('%H:%M:%S')}",
            "attribute_name": "Preview system"
        })
        description = "test block showing"

ScreenRecording2025-07-02at8 55 42AM-ezgif com-video-to-gif-converter

Test cases

Added for test_preview_value_falls_back_to_default and test_preview_value

@Tombow1 Tombow1 marked this pull request as ready for review July 2, 2025 18:26
@lb- lb- added type:Enhancement status:Needs Review component:Preview Page lives preview functionality, viewing drafts labels Jul 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
component:Preview Page lives preview functionality, viewing drafts status:Needs Review type:Enhancement
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants