我的 Django 代码插入新行而不是更新现有行时遇到问题。这里的许多人都曾就类似问题寻求帮助,但通常他们忘记设置instance
为form = SomeModelForm(request.POST or None, instance=some_model_instance)
. 我似乎做得对,但它仍然没有保存现有数据。
另一张海报也有完全相同的问题(当我想要 UPDATE 时,请参阅 Django 表单 INSERTs)。看起来给他解决问题的代码解决了这个问题,但是当他问到时,没有人解释为什么它会起作用!
看法
if form_type == "edit_event":
# we need to load all the data based on the event_id
event_id = request.POST['event_id'] or None
event_to_edit = mapDataManager.getEvent(event_id)
if event_to_edit and mapDataManager.userCreatedEvent(request.user, event_to_edit):
# this user actually created this event
# let them edit it
event_form = EventModelForm(request.POST or None, instance=event_to_edit)
location_form = LocationModelForm(request.POST or None, instance=event_to_edit.location)
list_of_event_scheds = EventSchedule.objects.filter(pk=event_id).values()
event_sched_formset = EventScheduleModelFormSet(request.POST or None, initial=list_of_event_scheds)
if event_form and location_form and event_sched_formset:
if event_form.is_valid() and location_form.is_valid() and event_sched_formset.is_valid():
# update event
mapDataManager.updateEvent(event_form, location_form, event_sched_formset)
# redirect
return HttpResponseRedirect(reverse('map'))
else:
# set feedback to show edit event form
feedback = "edit_event"
更新事件()
def updateEvent(self, event_form, location_form, event_sched_forms):
event = event_form.save(commit=False)
location = location_form.save()
event.location = location
event.save()
for event_sched_form in event_sched_forms: # loop through formset
event_sched = event_sched_form.save(commit=False)
event_sched.event = event
event_sched.save()
谁能帮我吗?我错过了一些非常基本的东西吗?
编辑:澄清一下,我的所有表格都没有更新,所有表格都在插入。根据丹尼尔的建议,我认为我需要使用表单集来链接正在编辑的所有三个模型表单。