import json from collections import UserList from django.conf import settings from django.core.exceptions import ValidationError from django.forms.renderers import get_default_renderer from django.utils import timezone from django.utils.html import escape, format_html_join from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ def pretty_name(name): """Convert 'first_name' to 'First name'.""" if not name: return '' return name.replace('_', ' ').capitalize() def flatatt(attrs): """ Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. In the case of a boolean value, the key will appear without a value. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string. The result is passed through 'mark_safe' (by way of 'format_html_join'). """ key_value_attrs = [] boolean_attrs = [] for attr, value in attrs.items(): if isinstance(value, bool): if value: boolean_attrs.append((attr,)) elif value is not None: key_value_attrs.append((attr, value)) return ( format_html_join('', ' {}="{}"', sorted(key_value_attrs)) + format_html_join('', ' {}', sorted(boolean_attrs)) ) class RenderableMixin: def get_context(self): raise NotImplementedError( 'Subclasses of RenderableMixin must provide a get_context() method.' ) def render(self, template_name=None, context=None, renderer=None): return mark_safe((renderer or self.renderer).render( template_name or self.template_name, context or self.get_context(), )) __str__ = render __html__ = render class RenderableFormMixin(RenderableMixin): def as_p(self): """Render as

elements.""" return self.render(self.template_name_p) def as_table(self): """Render as elements excluding the surrounding tag.""" return self.render(self.template_name_table) def as_ul(self): """Render as
  • elements excluding the surrounding