我有一个Formset的下面的视图,但是当我保存表单时,它不会保存对数据库的更改吗?
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))
答案 0 :(得分:1)
我怀疑formset无效,但是没有显示带有错误的formset,而是返回重定向。您应该将重定向移动到一个级别,进入if
语句:
if formset.is_valid():
...
return HttpResponseRedirect(reverse("Pipettes.views.month", args=(year, month)))
更新:如果您的formset未经过验证,但您在页面上未看到任何错误,那么您的formset呈现可能无效。出于测试目的,尝试使用最简单的模板:
<table>
{{ formset }}
</table>
另请注意,formset.save(commit=False)
已删除的对象不会自动删除。请参阅文档this chapter中的旁注。