在formset验证之前防止模型保存

时间:2013-10-21 12:01:13

标签: django django-forms

如何在formset验证之前阻止模型保存?代码例子:

form = StockMovementForm(data=data)
Formset = inlineformset_factory(StockMovement, StockMovement.products.through, extra=2, can_delete=False)
if form.is_valid():
  stock_movement = form.save()
  formset = Formset(data=data, instance=stock_movement)
  if formset.is_valid():
    formset.save()

(StockMovementForm用于创建新的* stock_movement *)

我希望在检查 formset 的有效性后保存表单

我找到了类似的东西:

form = StockMovementForm(data=data)
Formset = inlineformset_factory(StockMovement, StockMovement.products.through, extra=2, can_delete=False)
formset = Formset(data=data)
if form.is_valid():
  if formset.is_valid():
    stock_movement = form.save()
    objects = formset.save(commit=False)
    for object in objects:
      object.movement = stock_movement
      object.save()

但我不知道这是不是一个好方法(找到here)。

1 个答案:

答案 0 :(得分:3)

我会检查表格和表格集的有效性:

form = StockMovementForm(data=data)
Formset = inlineformset_factory(StockMovement,
    StockMovement.products.through, extra=2, can_delete=False)
formset = Formset(data=data)
if form.is_valid() and formset.is_valid():
    stock_movement = form.save()
    objects = formset.save(commit=False)
    for object in objects:
      object.movement = stock_movement
      object.save()