2016-07-26 81 views
-1

所以問題是我無法從窗體保存ManyToManyField。無法保存ManyToManyField

forms.py

class addGoods(forms.Form): 
    ... 

    permission = form['permission'], 

    ... 

models.py

class Add_good(models.Model): 
    ... 

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

    ... 

views.py

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

    if form.is_valid(): 

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

我試圖做這樣的事情,但也有錯誤

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() 

回溯:

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

什麼是錯誤? – khajvah

+0

@khajvah加追蹤 –

+1

那麼,錯誤是關於不同的問題。你還沒有發佈足夠的代碼來找到它。 「許可」來自哪裏? – khajvah

回答

2

的問題是在這裏: newGood = Add_good(permission = form['permission'])

權限是多對多領域,使您的表不直接具有permision場,所以不能採取論據。您可以創建模型條目,然後添加的權限:

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

另外,你的表格將不會從權限讓模特,你只是做permission = form['permission'],所以您需要進行手動查詢您的觀點,而不是/在for循環中。