views:

33

answers:

2

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?

+1  A: 

Maybe create a custom widget...

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

Matthew J Morrison
A customer widget would replace all textareas I think. I wish I could give a half point though as it pointed me in the right direction.
StephenPaulger
@StephenPaulger you can award a point but not accept as the answer, that's what points are for.
Matthew J Morrison
+1  A: 

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.

StephenPaulger
Or, I was going to suggest you try something like Codemirror (http://codemirror.net/) which lots more, too
stevejalim
I don't think I need to use codemirror on this as hopefully the JSON won't ever be massive but it's certainly a very useful thing to know about. Thanks.
StephenPaulger