Add dynamic fields through django admin
I've looked around the stack but I cant find any answers. So I have a model like this:
class DynamicModel(models.Model):
config = models.JSONField()
def __str__(self):
return self.config
what I want to do here now is to show the json field key-value pairs as standalone fields and also be able to edit them in the same way, like if they were each one a different field. This was the best way I could come up to create dynamic fields. So if I have a jsonfield like this:
{
"age": 23,
"name": "John Doe",
"gender": "Male"
}
I would have an `Age` field where I can edit the value or even remove the field alotgether. The changes would then reflect to the `JSONField`.
My approach is like this:
# forms.py
from django import forms
from .models import DynamicModel
class DynamicModelForm(forms.ModelForm):
class Meta:
model = DynamicModel
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Check if 'config' is in the fields
if 'config' in self.fields:
# Extract JSON data from the instance or initialize an empty dictionary
json_data = self.instance.config if self.instance and 'config' in self.instance else {}
# Loop through the JSON data and add individual fields
for key, value in json_data.items():
# Add a CharField for each key
self.fields[key] = forms.CharField(initial=value, required=False)
self.fields[key].label = key
self.fields[key].widget.attrs.update({'style': 'display:block;'})
# Remove the original JSON field
self.fields.pop('config', None)
def clean(self):
cleaned_data = super().clean()
json_data = cleaned_data.get('config', {})
# Loop through the JSON data and add individual fields
for key, value in json_data.items():
cleaned_data[key] = value
return cleaned_data
# admin.py
from django.contrib import admin
from .models import DynamicModel
class DynamicModelAdmin(admin.ModelAdmin):
form = DynamicModelForm
list_display = ['config']
admin.site.register(DynamicModel, DynamicModelAdmin)
but this doesnt seem to solve the problem. Any help appreciated.
An idea could be to work with an emty ModelForm that is then poulated dynamically:
class DynamicModelForm(forms.ModelForm):
class Meta:
model = DynamicModel
fields = []
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields.pop('config', None)
json_data = self.instance.config or {}
for key, value in json_data.items():
# Add a CharField for each key
self.fields[key] = forms.CharField(initial=value, required=False)
self.fields[key].label = key
self.fields[key].widget.attrs.update({'style': 'display:block;'})
def save(self, *args, **kwargs):
json_data = self.instance.config or {}
cleaned_data = self.cleaned_data
data = self.cleaned_data
for key, value in json_data.items():
config[key] = cleaned_data.get(key, value)
self.instance.config = config
return super().save(*args, **kwargs)
We thus add fields, more or less like you defined this yourself. When we want to save the item, we then regroup the fields into a dictionary, and save this to the instance.