Django ModelForm ManyToManyField无法更新选定的值

2024-06-25 23:27:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python3.4在django1.8中构建我的第一个项目。我有以下型号的盖子模型.py公司名称:

class Lid(models.Model):
    ...
    vereniging = models.ManyToManyField(Vereniging, blank=True)

我使用以下模型,表单.py在

^{pr2}$

当我使用这个ModelForm创建一个表单来创建一个新对象时,会出现一个多个选择框,我可以选择多个verening对象。这是我的观点视图.py公司名称:

def add_lid(request):
    if request.method == 'POST':
        form = LidForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            messages.success(request, 'Succes.')
            return HttpResponseRedirect(reverse('leden:home'))
    else:
        form = LidForm()
    return render(request, 'leden/lid/addlid.html', {'formset': form})

但是,当我想编辑我的对象时,我无法更改选定的verening对象。在

def edit_lid(request, lid_id):
    lid = get_object_or_404(Lid, pk=lid_id)
    if request.method == 'POST':
        form = LidForm(request.POST, request.FILES, instance=lid)
        if form.is_valid():
            nieuwlid = form.save(commit=False)
            nieuwlid.inschrijving_oras = lid.inschrijving_oras
            nieuwlid.save()
            messages.success(request, 'Success.')
            return HttpResponseRedirect(reverse('leden:lid', kwargs={'lid_id': lid_id}))
    else:
        form = LidForm(instance=lid)
    return render(request, 'leden/lid/editlid.html', {'formset': form, 'lid': lid})

基本上,当我的许多对象都是可以建模的时候,我只能用这个形式来建立关系。我无法更新这些m2m关系。你知道我做错了什么吗?在


Tags: 对象py模型formidreturnifrequest
1条回答
网友
1楼 · 发布于 2024-06-25 23:27:41

使用save_m2m()。来自the docs

Another side effect of using commit=False is seen when your model has a many-to-many relation with another model. If your model has a many-to-many relation and you specify commit=False when you save a form, Django cannot immediately save the form data for the many-to-many relation. This is because it isn’t possible to save many-to-many data for an instance until the instance exists in the database.

To work around this problem, every time you save a form using commit=False, Django adds a save_m2m() method to your ModelForm subclass. After you’ve manually saved the instance produced by the form, you can invoke save_m2m() to save the many-to-many form data.

相关问题 更多 >