我已经使用此accepted answer
实现了内联formset我在保存formset时遇到问题,它不会删除记录
我们可以将其追踪到DEFINED_PORT
:
formsets save method
如果我们深入研究def form_valid(self, form):
'''Handle saving of the project membership formset
'''
context = self.get_context_data()
project_memberships = context['projectmembership_formset']
if project_memberships.is_valid():
self.object = form.save()
project_memberships.instance = self.object
project_memberships.save()
方法,我们就会:
save
我发现def save_existing_objects(self, commit=True):
self.changed_objects = []
self.deleted_objects = []
if not self.initial_forms:
return []
saved_instances = []
forms_to_delete = self.deleted_forms
for form in self.initial_forms:
obj = form.instance
# If the pk is None, it means either:
# 1. The object is an unexpected empty model, created by invalid
# POST data such as an object outside the formset's queryset.
# 2. The object was already deleted from the database.
if obj.pk is None:
continue
if form in forms_to_delete:
self.deleted_objects.append(obj)
self.delete_existing(obj, commit=commit)
elif form.has_changed():
self.changed_objects.append((obj, form.changed_data))
saved_instances.append(self.save_existing(form, obj, commit=commit))
if not commit:
self.saved_forms.append(form)
return saved_instances
的{{1}}为空,因此不会发生删除。
pk
数据:
obj
为什么对象没有POST
且未被删除?
答案 0 :(得分:-1)
根据Class based viewINline formset
的答案 get_context_data
中包含POST
数据的UpdateView
也需要获得一个实例。
if self.request.POST:
context['projectmembership_formset'] = ProjectMembershipFormSet(
self.request.POST,
instance=self.object
)