JsonField in Django Admin as Inline
I have a JsonField in my Model, its structure is a dict.
class MyModel:
final_result = models.JSONField()
But it's pretty big, and it's hard to edit it with any JSON widget. So I thought, that maybe I need to parse/split it to several 'custom' fields.
jsonfield = {
"key1": "value1",
"key2": "value2",
"key3": [
{"inner_key_1": "inner_value_1", "inner_key_2": "inner_value_2", etc}
]
}
Given this JSON data, I would like to have fields: key1, key2 (which is easy), and here's the problem - key3, which is list of dicts.
Can I somehow display them like Inlines? With fields - inner_key_1, inner_key_2 (etc) So I can
- edit each element of list
- delete element with button
- add another element with preset fields
When I try to use inlines - it says it needs a model, but I don't have a model for this json. Proxy models and abstract models give errors. Forms, formsets (AI recommendations) don't work too.
I tried using inlines, forms, formsets, with a help from AI))
If you tried many packages and still no result, you can try 2 different ways:
Option 1: Create that specific page custom, completely from scratch.
This gives you full control over layout, logic, and output (HTML/JSON).
Option 2: Edit an existing Django admin HTML page and inject your JSON (or any custom part).
Example for a model’s change form:
# admin.py
class MyModelAdmin(admin.ModelAdmin):
change_form_template = "admin/myapp/mymodel/change_form.html"
def render_change_form(self, request, context, *args, **kwargs):
context["extra_json"] = {
"key1": "value1",
"key2": "value2",
"key3": [
{"inner_key_1": "inner_value_1",
"inner_key_2": "inner_value_2",
etc}
]}
return super().render_change_form(request, context, *args, **kwargs)
{# templates/admin/myapp/mymodel/change_form.html #}
{% extends "admin/change_form.html" %}
{% block after_related_objects %}
<div class="custom-block">
<h3>Extra JSON Data</h3>
<pre>{{ extra_json|safe }}</pre>
</div>
{% endblock %}