Django:在保存从form.Forms扩展的表单时使用save(commit = false)

时间:2018-10-03 12:56:41

标签: python django django-forms django-views

我有一个多对多字段,为了保存从表单中检索到的数据,最初,我必须保存该表的一个实例,否则,我会收到类似以下的错误:

  

在使用这种多对多关系之前,“订单:无”必须为字段“ id”具有一个值。

但是问题是当我有2个保存方法被调用时,它们还创建2个不同的日志(在第一个save()处创建实例,并在字母1处编辑实例),这导致混乱。因此,我希望能够在第一个commit=Falsesave(),并在第二个ModalForm中完成保存。 Commit用于form.Forms,但是我的表单扩展了if request.method == 'POST': form = OrderAddForm(request.POST) if form.is_valid(): order = Order() order.user = request.user order.save() order.ordered_materials.set(form.cleaned_data['ordered_materials']) order.location = form.cleaned_data['location'] order.note = form.cleaned_data['note'] form.save() else: form = OrderAddForm()

views.py

class OrderAddForm(forms.Form):
  ordered_materials = forms.ModelMultipleChoiceField(
      queryset=Material.objects.all(),
  )
  location = forms.CharField()
  note = forms.CharField()

  ordered_materials.widget.attrs.update({'id': 'materialsid',
                                 'class': 'form-control',
                                 })

forms.py

class Order(models.Model):

user = models.ForeignKey(User,
                         on_delete=models.CASCADE)

ordered_materials = models.ManyToManyField('Material')
location = models.CharField(max_length=500)
note = models.CharField(max_length=30,
                        verbose_name="Note")

STATUS = (
    ('n', 'None'),
    ('a', 'Accepted'),
    ('r', 'Rejected'),
)

status_name = models.CharField(max_length=1,
                               choices=STATUS,
                               default='n')

def __str__(self):
    return str(self.id)

models.py

{{1}}

1 个答案:

答案 0 :(得分:2)

设置多对多字段后,无需保存对象。因此,您应该能够重新安排代码,以便只调用一次save()

if form.is_valid():
    order = Order()
    order.user = request.user
    order.location = form.cleaned_data['location']
    order.note = form.cleaned_data['note']
    order.save()

    order.ordered_materials.set(form.cleaned_data['ordered_materials'])