Created
January 5, 2017 15:28
-
-
Save bmihelac/5f7b9f1580cd711415faf1516a715f63 to your computer and use it in GitHub Desktop.
Example validating wagtail StructBlock
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
Fantastic! Thank you for this.