在Django中使用内联表单集删除模型对象可以通过以下步骤实现:
Parent
和Child
,并且Child
模型具有一个外键关联到Parent
模型。ChildInlineFormSet
类,并使用inlineformset_factory
函数来创建它。from django.forms import inlineformset_factory
from .models import Parent, Child
ChildInlineFormSet = inlineformset_factory(Parent, Child)
__init__
方法中传递instance
参数来创建内联表单集,并将其作为一个字段添加到表单中。from django import forms
from .models import Parent
class ParentForm(forms.ModelForm):
class Meta:
model = Parent
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
instance = kwargs.get('instance')
self.child_formset = ChildInlineFormSet(instance=instance, data=self.data)
def is_valid(self):
return super().is_valid() and self.child_formset.is_valid()
def save(self, commit=True):
parent = super().save(commit=commit)
self.child_formset.instance = parent
self.child_formset.save()
return parent
formset.deleted_objects
属性获取被删除的子模型对象列表。from django.shortcuts import render, get_object_or_404, redirect
from .forms import ParentForm
def delete_model(request, parent_id):
parent = get_object_or_404(Parent, pk=parent_id)
if request.method == 'POST':
form = ParentForm(request.POST, instance=parent)
if form.is_valid():
formset = form.child_formset
for obj in formset.deleted_objects:
obj.delete()
form.save()
return redirect('parent_detail', parent_id=parent_id)
else:
form = ParentForm(instance=parent)
return render(request, 'delete_model.html', {'form': form})
form.as_p
渲染父模型表单字段,以及使用form.child_formset.as_table
渲染内联表单集。<form method="POST">
{% csrf_token %}
{{ form.as_p }}
{{ form.child_formset.as_table }}
<input type="submit" value="Save">
</form>
这样,在Django中就可以通过使用内联表单集删除模型对象了。
对于推荐的腾讯云相关产品和产品介绍链接地址,可以参考腾讯云的官方文档:https://cloud.tencent.com/document/product/301/3278
领取专属 10元无门槛券
手把手带您无忧上云