Skip to content

Instantly share code, notes, and snippets.

@bmihelac
Created January 5, 2017 15:28
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmihelac/5f7b9f1580cd711415faf1516a715f63 to your computer and use it in GitHub Desktop.
Save bmihelac/5f7b9f1580cd711415faf1516a715f63 to your computer and use it in GitHub Desktop.
Example validating wagtail StructBlock
from django.core.exceptions import ValidationError
from django.forms.utils import ErrorList
from wagtail.wagtailcore import blocks
class MyLinkBlock(blocks.StructBlock):
"""
Example validating StructBlock.
"""
link = blocks.CharBlock(required=False)
page = blocks.PageChooserBlock(required=False)
def clean(self, value):
result = super(MyLinkBlock, self).clean(value)
errors = {}
if value['link'] and value['page']:
errors['link'] = ErrorList([
'This should not be set when Page is selected',
])
if errors:
raise ValidationError(
'Validation error in StructBlock',
params=errors
)
return result
@coredumperror
Copy link

Fantastic! Thank you for this.

@pySilver
Copy link

why not simply:

class ButtonBlock(blocks.StructBlock):
    """An external or internal URL."""

    anchor = blocks.CharBlock(label=_("Anchor text"), required=True)

    target_page = blocks.PageChooserBlock(
        label=_("Page"),
        required=False,
        help_text=_("If selected, this url will be used first"),
    )
    target_url = blocks.URLBlock(
        label=_("URL"),
        required=False,
        help_text=_("If added, this url will be used secondarily to the target page"),
    )

    class Meta:
        template = "core/blocks/button.html"
        icon = "fal fa-rectangle-wide"
        label = _("Button")
        value_class = LinkStructValue

    def clean(self, value):
        if not any([value["target_page"], value["target_url"]]):
            raise ValidationError(_("Target page or URL should be specified."))

        return super().clean(value)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment