Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin: Alter how data is displayed

I have a model with a json field. The contents of which may or may not be pretty-printed, I don't really mind either way as long as the data is valid. However when it is displayed in django admin I would like for the contents of the field to be pretty printed so that it is easy to read. I don't mind if this means the pretty printed version is then saved.

Any tips on how to do this?

like image 505
Stephen Paulger Avatar asked Feb 05 '26 23:02

Stephen Paulger


2 Answers

Answering my own question...

After reading the documentation near what Matthew J Morrison pointed me to. I discovered I could add a javascript to alter things.

to my ModelAdmin I added

class Media:
    js = ("/site_media/json2.js", "/site_media/custom.js")

json2.js is from Douglas Crockford's website

custom.js is

django.jQuery(document).ready(function() {
    data = JSON.parse(django.jQuery("#id_json")[0].value);
    django.jQuery("#id_json")[0].value = JSON.stringify(data, null, 4)
});

Easy when you know how.

like image 141
Stephen Paulger Avatar answered Feb 07 '26 12:02

Stephen Paulger


Maybe create a custom widget...

http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_overrides

like image 44
Matthew J Morrison Avatar answered Feb 07 '26 12:02

Matthew J Morrison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!