import json

from django.forms import Textarea
from django.utils.html import format_html


class PrettyJSONWidget(Textarea):
    """
    Custom widget that can pretty print JSONField data.
    """

    def render(self, name, value, attrs=None, renderer=None):
        try:
            parsed = json.loads(value)
            pretty_printed = json.dumps(parsed, indent=4, sort_keys=True)
        except (TypeError, ValueError):
            pretty_printed = value
        html = super().render(name, pretty_printed, attrs=attrs, renderer=renderer)
        return format_html("<pre>{0}</pre>", html)
