Django Form不会向ManyToManyField添加新对象,而是在其他对象之间切换

时间:2019-05-24 22:09:09

标签: django django-models django-forms django-views

我正在尝试通过将新用户添加到权限来更新对象,并且如果我要更新它,则不会添加用户,而是将具有此权限的其他用户设置为未选中。

views.py

elif(request.POST['custom'] == 'assign'):
    guest = Departments.objects.get(id=request.POST['id'])
    print(request.POST)
    form = AddDepartment()
    form2 = AssignDepartment(data=request.POST, instance=guest)
    if form2.is_valid():
        department = Departments.objects.get(department = 
        form2.cleaned_data['department'])
        print(form2.cleaned_data['user'])
        print(form2.cleaned_data['user'][0].id)

 department.user.add(Person.objects.get(id=form2.cleaned_data['user'][0].id))
form2.save()

models.py

 department = models.CharField(max_length=60, verbose_name='Oddziały', unique=True)
    user = models.ManyToManyField('Person', blank=True, verbose_name='Pracownik')

1 个答案:

答案 0 :(得分:0)

我找到了更改模型的解决方案。我从部门中删除字段用户,并在表Person中创建M2M字段。它现在可以完美运行。