Skip to content

Instantly share code, notes, and snippets.

@nwjlyons
Last active June 26, 2018 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nwjlyons/e4929fbb256c49562045364d39d59680 to your computer and use it in GitHub Desktop.
Save nwjlyons/e4929fbb256c49562045364d39d59680 to your computer and use it in GitHub Desktop.
Wagtail NonFieldErrors for Blocks
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
{# 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>
@nwjlyons
Copy link
Author

block-non-field-error

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