django Formset 不会保存

django Formset won't save

我有下面的表单集视图,但是当我保存表单时它没有保存对数据库的更改?

def schedule(request, year, month, day):
     EntriesFormset = modelformset_factory(Entry, extra = 1, exclude=("creator",   "date"),can_delete=True)

    if request.method == 'POST':
        formset = EntriesFormset(request.POST)
        if formset.is_valid():
        # add current user and date to each entry & save
            entries = formset.save(commit=False)
            for entry in entries:
                entry.creator = request.user
                entry.date = date(int(year), int(month), int(day))
                entry.save()
        return HttpResponseRedirect(reverse("Pipettes.views.month", args=(year, month)))

    else:
    # display formset for existing enties and one extra form
        formset = EntriesFormset(queryset=Entry.objects.filter(date__year=year,date__month=month, creator=request.user))
    return render_to_response("Scheduler.html", add_csrf(request, entries=formset, year=year,
        month=month, day=day))

我怀疑表单集无效,但您没有显示带有错误的表单集,而是返回了重定向。您应该将重定向向右移动一级,进入 if 语句:

if formset.is_valid():
    ...
    return HttpResponseRedirect(reverse("Pipettes.views.month", args=(year, month)))

更新:如果您的表单集未通过验证但您在页面上没有看到任何错误,那么您的表单集呈现可能无效。出于测试目的,尽量使用最简单的模板:

<table>
    {{ formset }}
</table>

另请注意,formset.save(commit=False) 删除的对象不会自动删除。请参阅文档 this chapter 中的旁注。