Newsletter
TechAnV Blog
Get updates on security engineering, Rust, eBPF, and DevSecOps. No spam, unsubscribe anytime.
Check your inbox and click the confirmation link to complete your subscription.
Pretty-printing all read-only JSON in the Django admin#
I have a bunch of models with JSON fields that are marked as read-only in the Django admin - usually because they’re recording the raw JSON that was imported from an API somewhere to create an object, for debugging purposes.
Here’s a pattern I found for pretty-printing ANY JSON value that is displayed in a read-only field in the admin. Create a template called admin/change_form.html and populate it with the following:
1{% extends "admin/change_form.html" %}2{% block admin_change_form_document_ready %}3{{ block.super }}4<script>5Array.from(document.querySelectorAll('div.readonly')).forEach(div => {6 let data;7 try {8 data = JSON.parse(div.innerText);9 } catch {10 // Not valid JSON11 return;12 }13 div.style.whiteSpace = 'pre-wrap';14 div.style.fontFamily = 'courier';15 div.style.fontSize = '0.9em';16 div.innerText = JSON.stringify(data, null, 2);17});18</script>19{% endblock %}This JavaScript will execute on every Django change form page, scanning for div.readonly, checking to see if the div contains a valid JSON value and pretty-printing it using JavaScript if it does.
It’s a cheap hack and it works great.