class Person(models.Model):
name = models.CharField(max_length=100)
class Entry(models.Model):
text = models.CharField(max_length=100)
person = models.ManyToManyField(Person, blank=True, null=True)
class MyModelForm(forms.ModelForm):
class Meta:
model = Entry
In my view, I need to add pk id's to a submitted form before saving it.
data = request.POST.copy()
# 'person' is a ManyToManyField to a 'Person' model
# a form would normally send multiple id's as POST in this format -> u'id': [u'1', u'2']
# u'1,2' (an example) is a str variable accessible to the view
data[u'person'] = u'1,2'.split(",")
form = MyModelForm(data)
if form.is_valid():
form.save()
This gives me:
int() argument must be a string or a number, not 'list'
Which is fair enough. It does work in case of:
data[u'person'] = u'1'
I also tried this with no success:
new_form = form.save(commit=False)
new_form.person = u'1,2'.split(",")
new_form.save()
form.save_m2m()
How can I save multiple id's to this ManyToManyField?
Must be easy but I am missing the point.
EDIT: The desired result is one new instance of MyModelForm (in the 'entry' table) with all id's stored for form.person (multiple records in the 'entry_person' table).
UPDATE: I seem to have isolated the problem.
If I do:
data = {}
data[u'person'] = u'1,2'.split(",")
It does work as the result is:
{u'person': [u'1', u'2'],}
If I do:
data = request.POST.copy()
data[u'person'] = u'1,2'.split(",")
It does NOT work (gives the error described above) as the result is:
<QueryDict: {u'person': [[u'1', u'2']],}>
So all I need is to have
<QueryDict: {u'person': [u'1', u'2'],}>
Any suggestions how?