user6286625
user6286625

Reputation:

Can't save ManyToManyField

So the problem is that I can't save ManyToManyField from form.

Here is my form: forms.py

class addGoods(forms.Form):
   ...

    permission = form['permission'],

   ...

My model: models.py

class Add_good(models.Model):
   ...

    permission = models.ManyToManyField(Permission, related_name="+")

   ...

In my view if request method equals "POST", I try to save these data into my model: views.py

if request.method == "POST":
    form = addGoods(request.POST)

    if form.is_valid():

        form = form.cleaned_data
        newGood = Add_good(permission = form['permission'])

I have tried to do something like this(see below), but there is also errors: views.py

if request.method == "POST":
        form = addGoods(request.POST)

        if form.is_valid():

            form = form.cleaned_data
            newGood = Add_good(permission = form['permission'])

            to_do_list = newGood.save(commit=False)
            for permis in form['permission']:
                to_do_list.permission.add(permis)
                to_do_list.save()
            newGood.save_m2m()

And my traceback Traceback:

Exception Type: TypeError at /goods/add
Exception Value: 'permission' is an invalid keyword argument for this function

So as you can see there is something wrong with permission and I can't save it

Upvotes: 0

Views: 101

Answers (1)

khajvah
khajvah

Reputation: 5090

The problem is here: newGood = Add_good(permission = form['permission'])

Permission is ManyToMany field, so your table doesn't directly have permision field, so it can't take that argument. You can create the model entry then add the permission:

newGood = Add_good.objects.create(...)
newGood.permission.add(Permissions.objects.get(...))

Also, your form won't make models from permissions as you just did permission = form['permission'], so you will need to make a manual query in your view instead of/in the for loop.

Upvotes: 2

Related Questions