Add widget to pretty print JSONFields in admin
This commit is contained in:
parent
a3feadc364
commit
5955ad83a3
|
|
@ -0,0 +1,19 @@
|
||||||
|
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)
|
||||||
|
|
@ -1,11 +1,16 @@
|
||||||
from django.contrib import admin
|
from django.contrib import admin
|
||||||
|
from django.db.models import JSONField
|
||||||
|
|
||||||
|
from vbv_lernwelt.core.admin_utils import PrettyJSONWidget
|
||||||
from vbv_lernwelt.course.models import CourseSession, CourseSessionUser
|
from vbv_lernwelt.course.models import CourseSession, CourseSessionUser
|
||||||
from vbv_lernwelt.learnpath.models import Circle
|
from vbv_lernwelt.learnpath.models import Circle
|
||||||
|
|
||||||
|
|
||||||
@admin.register(CourseSession)
|
@admin.register(CourseSession)
|
||||||
class CourseSessionAdmin(admin.ModelAdmin):
|
class CourseSessionAdmin(admin.ModelAdmin):
|
||||||
|
formfield_overrides = {
|
||||||
|
JSONField: {"widget": PrettyJSONWidget(attrs={"rows": 16, "cols": 80})},
|
||||||
|
}
|
||||||
date_hierarchy = "created_at"
|
date_hierarchy = "created_at"
|
||||||
list_display = [
|
list_display = [
|
||||||
"title",
|
"title",
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue