Last active
June 26, 2018 16:02
-
-
Save nwjlyons/e4929fbb256c49562045364d39d59680 to your computer and use it in GitHub Desktop.
Wagtail NonFieldErrors for Blocks
This file contains 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
class NonFieldErrors: | |
def __init__(self, *args, **kwargs): | |
super().__init__(*args, **kwargs) | |
self.non_field_errors = [] | |
self.meta.form_template = 'struct.html' | |
def get_form_context(self, value, prefix='', errors=None): | |
context = super().get_form_context(value, prefix, errors) | |
context['non_field_errors'] = self.non_field_errors | |
return context | |
def add_non_field_errors(self, errs: List[str]) -> None: | |
self.non_field_errors = errs | |
raise ValidationError("The page could not be saved due to validation errors", params={ | |
NON_FIELD_ERRORS: ErrorList(errs) | |
}) | |
class Person(NonFieldErrors, blocks.StructBlock): | |
name = blocks.CharField() | |
age = blocks.IntegerField() | |
def clean(self, value) | |
value = super().clean(value) | |
if value["name"] == "Joe Bloggs" and value["age"] >= 100: | |
self.add_non_field_errors(["I don't believe you."]) | |
return value |
This file contains 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
{# Original file: https://github.com/wagtail/wagtail/blob/master/wagtail/admin/templates/wagtailadmin/block_forms/struct.html #} | |
<div class="{{ classname }}"> | |
{% if non_field_errors %} | |
<div class="messages"> | |
<ul> | |
{% for err in non_field_errors %} | |
<li class="error">{{ err }}</li> | |
{% endfor %} | |
</ul> | |
</div> | |
<br> | |
{% endif %} | |
{% if help_text %} | |
<div class="object-help help">{{ help_text }}</div> | |
{% endif %} | |
<ul class="fields"> | |
{% for child in children.values %} | |
<li{% if child.block.required %} class="required"{% endif %}> | |
{% if child.block.label %} | |
<label{% if child.id_for_label %} for="{{ child.id_for_label }}"{% endif %}>{{ child.block.label }}:</label> | |
{% endif %} | |
{{ child.render_form }} | |
</li> | |
{% endfor %} | |
</ul> | |
</div> |
Author
nwjlyons
commented
Jun 26, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment