Skip to content

dj-models: PrettyJSONMixin for admin JSONField display#10

Open
ashbrener wants to merge 1 commit into
dvf:masterfrom
ashbrener:convention/pretty-json-widget
Open

dj-models: PrettyJSONMixin for admin JSONField display#10
ashbrener wants to merge 1 commit into
dvf:masterfrom
ashbrener:convention/pretty-json-widget

Conversation

@ashbrener
Copy link
Copy Markdown

@ashbrener ashbrener commented Apr 21, 2026

Summary

Adds a small, self-contained utility — PrettyJSONWidget + PrettyJSONMixin — that production codebases on this stack typically build independently. Django's default AdminTextareaWidget renders JSONField as a flat unindented blob; the widget pretty-prints with indent=2, sort_keys=True.

Motivation

If you have a JSONField anywhere in your models, the admin change view is hard to read without this. It's a ~15-line utility that gets reinvented in every project — worth codifying in dj-models so the next project doesn't do it again.

What changes

skills/dj-models/SKILL.md — new subsection under "Admin Rules":

  • PrettyJSONWidget(AdminTextareaWidget) — pretty-prints JSONField
  • PrettyJSONMixin — adds formfield_for_dbfield override on any admin that opts in
  • Opt-in per admin — no mandatory base class

Tradeoffs

  • Mixin over base class — chose mixin over a BaseAdminModel so the admin is opt-in. A base class would tie every admin to the widget even when the model has no JSONField.
  • JSONField only — deliberately narrow scope. ArrayField / HStoreField users can extend the mixin.
  • Placement in MRO — mixin goes before admin.ModelAdmin so its formfield_for_dbfield fires first.

Codify the PrettyJSONWidget + PrettyJSONMixin pattern that production
codebases on this stack independently build in project/admin_utils.py.

Django's default AdminTextareaWidget renders JSONField as a flat blob.
The mixin wires formfield_for_dbfield to use a widget that json.dumps
with indent=2 and sort_keys=True.

Opt-in via mixin, not mandatory base class — only apply it where the
model actually has a JSONField. Placed before admin.ModelAdmin in the
MRO so the override takes effect.
@ashbrener ashbrener force-pushed the convention/pretty-json-widget branch from daaf9d5 to 6e5d5e1 Compare April 21, 2026 05:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant