I have a model form in which I need to store an unknown number of helpers alongside a thing. The names can be serialised upon save, and that's not a problem. It's being able to clean and validate them upon submission.
The form looks like;
class ThingForm(forms.ModelForm):
"""
Form for the Thing
"""
owner = forms.CharField()
helpers = forms.CharField()
class Meta:
model = Thing
def save(self, *args, **kwargs):
"""
Serialize helpers to JSON.
"""
...
And the model is using a JSONField to store the serialised helpers.
class Thing(models.Model):
owner = models.CharField()
helpers = JSONField()
I have JavaScript adding as many helpers as required with the same input name:
<input name="helpers" value="Fred" />
<input name="helpers" value="Joe" />
Which is returning a tuple of the helpers. The problem is that the if the form isn't valid - those names will be lost and the cleaning isn't working.
My first thought was to add to the form's constructor:
def __init__(self, *args, **kwargs):
super(ThingForm, self).__init__(*args, **kwargs)
try:
helpers = args[0].pop('helpers')
for name in helpers:
# Add a charfield, or something?
except:
pass
But I'm not really getting anywhere...