views:

660

answers:

3
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?

A: 

The split you entered returns the following:

[u'1', u'2']

To create multiple instances in your database you'd need to iterate over the list:

for x in u'1,2'.split(","):
  data[u'person'] = x
  form = MyModelForm(data)
  if form.is_valid():
    form.save()

Out of curiosity, why string to list conversion in the first place? Or is this just a general example

awithrow
Thank you! This creates n records of MyModelForm (each having 'person' = x from the for loop), where n = number of items in the []. What I need is to create one record of MyModelForm and store n id's for 'person'.
dmi
A: 

Try:

new_form.person = [int(x) for x in u'1,2'.split(",")]

This will set new_form.person to a list of ints, not a list of strings.

Matthew Christensen
Thank you! This does not work. TypeError: int() argument must be a string or a number, not 'list'
dmi