Using Django 1.11, one of my models is an array stored within a django-jsonfield field.
class MyModel(models.Model)
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
core = JSONField(blank=True, null=True, default=None)
I am using a ModelForm in a couple of views to create and edit new instances. Within the ModelForm I'm borrowing the django.contrib.postgres.forms.SimpleArrayField to parse the input into the field.
Adding a new model is fine, but in the edit version, the array gets pre-populated with what looks like the __str__ representation (eg an array of 1,2,3 becomes ['1','2','3'].
I'm getting around this by parsing the array into initial= for each form but I'd rather do this in one place (DRY) rather than having to repeat it inside each view and form instance.
Are there any hooks or methods (perhaps a custom widget?) that means I can do this just once in the form or somewhere else?
Snippet of the current view with hacky approach using initial=:
def edit_mymodel(id):
current_instance = MyModel.objects.get(pk=id)
if request.method == "GET":
form = MyModelForm(instance=current_instance,
initial={"core": ",".join(current_instance.core)}
)
return render(request, 'network_manager/edit.html',
{'form': form}
)
You can override __init__
class MyModelForm(ModelForm)
def __init__(self, *args, **kwargs):
super(MyModelForm, self).__init__(*args, **kwargs)
self.initial['core'] = ",".join(self.instance.core)