From 31966eab4f94de6d7fc470189b5315c725b33962 Mon Sep 17 00:00:00 2001 From: Matt Westcott Date: Thu, 12 Feb 2015 14:04:27 +0000 Subject: [PATCH] Add template filters to support widgets that implement render_with_errors --- .../templates/wagtailadmin/shared/field.html | 4 ++-- .../templatetags/wagtailadmin_tags.py | 24 +++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/wagtail/wagtailadmin/templates/wagtailadmin/shared/field.html b/wagtail/wagtailadmin/templates/wagtailadmin/shared/field.html index 7cb6c05c7..0a87112ad 100644 --- a/wagtail/wagtailadmin/templates/wagtailadmin/shared/field.html +++ b/wagtail/wagtailadmin/templates/wagtailadmin/shared/field.html @@ -4,7 +4,7 @@
{% block form_field %} - {{ field }} + {{ field|render_with_errors }} {% endblock %} {# This span only used on rare occasions by certain types of input #} @@ -14,7 +14,7 @@

{{ field.help_text }}

{% endif %} - {% if field.errors %} + {% if field|has_unrendered_errors %}

{% for error in field.errors %} {{ error|escape }} diff --git a/wagtail/wagtailadmin/templatetags/wagtailadmin_tags.py b/wagtail/wagtailadmin/templatetags/wagtailadmin_tags.py index 650e49f35..993b83ecc 100644 --- a/wagtail/wagtailadmin/templatetags/wagtailadmin_tags.py +++ b/wagtail/wagtailadmin/templatetags/wagtailadmin_tags.py @@ -150,3 +150,27 @@ class EscapeScriptNode(template.Node): return cls(nodelist) register.tag(EscapeScriptNode.TAG_NAME, EscapeScriptNode.handle) + + +# Helpers for Widget.render_with_errors, our extension to the Django widget API that allows widgets to +# take on the responsibility of rendering their own error messages +@register.filter +def render_with_errors(bound_field): + """ + Usage: {{ field|render_with_errors }} as opposed to {{ field }}. + If the field (a BoundField instance) has errors on it, and the associated widget implements + a render_with_errors method, call that; otherwise, call the regular widget rendering mechanism. + """ + widget = bound_field.field.widget + if bound_field.errors and hasattr(widget, 'render_with_errors'): + return widget.render_with_errors(bound_field.html_name, bound_field.value(), attrs={'id': bound_field.auto_id}, errors=bound_field.errors) + else: + return bound_field.as_widget() + +@register.filter +def has_unrendered_errors(bound_field): + """ + Return true if this field has errors that were not accounted for by render_with_errors, because + the widget does not support the render_with_errors method + """ + return bound_field.errors and not hasattr(bound_field.field.widget, 'render_with_errors')