我在一个页面中有formset和form,两者都是同时保存的。但是不保存事件时间的新记录,只更新旧记录。问题在哪里?
表单集:
class EventTimeForm(forms.ModelForm):
class Meta:
model = EventTime
fields = ['start_time']
widgets = {
'start_time': DateTimeWidget(usel10n=True, bootstrap_version=3)
}
EventTimeFormSet = modelformset_factory(EventTime, form=EventTimeForm, max_num=3, extra=3)
形式:
class CreateEventForm(forms.ModelForm):
class Meta:
model = Event
fields = ['title', 'description', 'location', 'duaration', 'private']
观点:
def create_event(request):
event_form = CreateEventForm(request.POST or None, prefix='event')
event_time_form = EventTimeFormSet(request.POST or None, prefix='eventtime')
context = {
'event_form': event_form,
'event_time_form': event_time_form,
}
if event_form.is_valid() and event_time_form.is_valid():
event = event_form.save()
event_time = event_time_form.save()
for obj in event_time:
obj.event.add(event)
return HttpResponseRedirect('/event-%s' %event.id)
return render(request, 'create_event.html', context)
模板:
<form method='POST' action=''>{%csrf_token%}
{{ event_time_form|crispy }}
{{ event_form|crispy}}
<input class="btn btn-primary" type="submit" value="Create" />
</form>