Skip to content

Instantly share code, notes, and snippets.

@mverleg
Created February 25, 2018 11:35
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mverleg/3292e29690456e81daff57654ef17986 to your computer and use it in GitHub Desktop.
django-bootstrap4 errors at fields
from bootstrap4.renderers import FormRenderer, FieldRenderer
from bootstrap4.text import text_value
class FieldErrorFormRenderer(FormRenderer):
"""
Adapted version of Bootstrap 4 FormRenderer, that shows error messages
at the field, rather than at the top.
"""
def _render(self):
return self.render_errors('non_fields') + self.render_fields()
class WithErrorFieldRenderer(FieldRenderer):
"""
Adapted version of Bootstrap 4 FieldRenderer, that shows error messages
at the field, rather than at the top.
"""
def add_field_errors(self, html):
if not self.field.errors:
return html
errhtml = '<div class="{0:s} alert alert-danger" role="alert">'.format(self.error_css_class)
for error in self.field.errors:
errhtml += '<p>' + error + '</p>'
errhtml += '</div>'
html += errhtml
return html
def _render(self):
# See if we're not excluded
if self.field.name in self.exclude.replace(' ', '').split(','):
return ''
# Hidden input requires no special treatment
if self.field.is_hidden:
return text_value(self.field)
# Render the widget
self.add_widget_attrs()
html = self.field.as_widget(attrs=self.widget.attrs)
self.restore_widget_attrs()
# Start post render
html = self.post_widget_render(html)
html = self.wrap_widget(html)
html = self.make_input_group(html)
html = self.append_to_field(html)
html = self.add_field_errors(html)
html = self.wrap_field(html)
html = self.add_label(html)
html = self.wrap_label_and_field(html)
return html
@mverleg
Copy link
Author

mverleg commented Feb 25, 2018

With these settings:

BOOTSTRAP4 = dict(
    form_renderers=dict(
        default='appname.form_renderer.FieldErrorFormRenderer',
    ),
    field_renderers=dict(
        default='appname.form_renderer.WithErrorFieldRenderer',
    ),
)

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