所以问题是我无法从表单中保存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 :(得分:2)
问题在于:
newGood = Add_good(permission = form['permission'])
权限是ManyToMany字段,因此您的表不直接具有permision
字段,因此它不能接受该参数。您可以创建模型条目,然后添加权限:
newGood = Add_good.objects.create(...)
newGood.permission.add(Permissions.objects.get(...))
此外,您的表单不会像刚刚permission = form['permission']
那样通过权限制作模型,因此您需要在视图中而不是/在for循环中进行手动查询。