From 2775a952f2fc42be4c7f675fa5a9fb275936e2e2 Mon Sep 17 00:00:00 2001 From: j Date: Thu, 28 Oct 2021 12:28:51 +0100 Subject: [PATCH] filters, list_editable, format json field --- app/text/admin.py | 9 ++++++++- app/video/admin.py | 12 +++++++++++- app/widgets.py | 21 +++++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 app/widgets.py diff --git a/app/text/admin.py b/app/text/admin.py index aed4364..6de2259 100644 --- a/app/text/admin.py +++ b/app/text/admin.py @@ -1,10 +1,15 @@ from django.contrib import admin +from django.db.models import JSONField from . import models +from ..widgets import PrettyJSONWidget @admin.decorators.register(models.Text) class TextAdmin(admin.ModelAdmin): + formfield_overrides = { + JSONField: {'widget': PrettyJSONWidget} + } list_display = ( '__str__', 'item', @@ -14,7 +19,9 @@ class TextAdmin(admin.ModelAdmin): 'public', 'position', ) - list_editable = ['public', 'language'] + list_editable = ['public', 'language', 'position'] + list_filter = ['language', 'public'] + def item(self, obj): return obj.data.get('item') def edit(self, obj): diff --git a/app/video/admin.py b/app/video/admin.py index 731ab1e..aea71e8 100644 --- a/app/video/admin.py +++ b/app/video/admin.py @@ -1,16 +1,26 @@ +import logging +import json + from django.contrib import admin +from django.db.models import JSONField from . import models - +from ..widgets import PrettyJSONWidget +logger = logging.getLogger(__name__) @admin.decorators.register(models.Film) class FilmAdmin(admin.ModelAdmin): + formfield_overrides = { + JSONField: {'widget': PrettyJSONWidget} + } list_display = ( '__str__', 'position', 'slug', 'public', ) + list_editable = ['public', 'position'] + list_filter = ['public'] #@admin.decorators.register(models.Edit) #class EditAdmin(admin.ModelAdmin): diff --git a/app/widgets.py b/app/widgets.py new file mode 100644 index 0000000..23797ce --- /dev/null +++ b/app/widgets.py @@ -0,0 +1,21 @@ +import logging +import json + +from django.forms import widgets + +logger = logging.getLogger(__name__) + +class PrettyJSONWidget(widgets.Textarea): + + def format_value(self, value): + try: + value = json.dumps(json.loads(value), indent=2, sort_keys=True, ensure_ascii=False) + # these lines will try to adjust size of TextArea to fit to content + row_lengths = [len(r) for r in value.split('\n')] + self.attrs['rows'] = min(max(len(row_lengths) + 2, 10), 30) + self.attrs['cols'] = min(max(max(row_lengths) + 2, 40), 120) + return value + except Exception as e: + logger.warning("Error while formatting JSON: {}".format(e)) + return super(PrettyJSONWidget, self).format_value(value) +