import json import warnings 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.deprecation import RemovedInDjango50Warning from django.utils.html import escape, format_html_join from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ from django.utils.version import get_docs_version 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) ) DEFAULT_TEMPLATE_DEPRECATION_MSG = ( 'The "default.html" templates for forms and formsets will be removed. These were ' 'proxies to the equivalent "table.html" templates, but the new "div.html" ' "templates will be the default from Django 5.0. Transitional renderers are " "provided to allow you to opt-in to the new output style now. See " "https://docs.djangoproject.com/en/%s/releases/4.1/ for more details" % get_docs_version() ) 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): renderer = renderer or self.renderer template = template_name or self.template_name context = context or self.get_context() if ( template == "django/forms/default.html" or template == "django/forms/formsets/default.html" ): warnings.warn( DEFAULT_TEMPLATE_DEPRECATION_MSG, RemovedInDjango50Warning, stacklevel=2 ) return mark_safe(renderer.render(template, 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