dmi
dmi

Reputation: 1916

Adding data to many-to-many field of a modelform within a view

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?

Upvotes: 1

Views: 5262

Answers (3)

dmi
dmi

Reputation: 1916

QueryDict.setlist(key, list_) solves this problem.

Answered in A workaround for Django QueryDict wrapping values in lists?

Upvotes: 1

Matthew Christensen
Matthew Christensen

Reputation: 1731

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.

Upvotes: 0

awithrow
awithrow

Reputation: 1113

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

Upvotes: 0

Related Questions