在 ModelFormSetView 中如何删除行
这是我的代码,该如何管理Django-extra-views中的删除行
我正在尝试使用ModelFormSetView
if formset.deleted_forms:
for obj in formset.deleted_forms:
obj.delete()
HTML
{{ formset.management_form }}
{% for object in formset %}
{% for hidden in formset.hidden_fields %}
{{ hidden }}
{% endfor %}
<tr class="formset" class="even pointer">{{ object.id }}
<td class=" ">{{ object.as_p }}</td>
<td class=""></td>
</tr>
{% endfor %}
查看
这是一般视图,我如何管理填写在此的
class MeasurementPropsUpdateViews(ModelFormSetView):
model = MeasurementProps
form_class= MeasurementPropsForm
template_name = "master/measurementprops_form.html"
def get_queryset(self):
pk = self.kwargs.get('pk')
current_user = self.request.user
return self.model.objects.filter(ProductName=pk, user=current_user)
def get_success_url(self):
return reverse("tailoringproducts")
def formset_valid(self, formset):
for docs_form in formset:
docs_form.save(commit=False)
if formset.deleted_forms:
for obj in formset.deleted_forms:
obj.delete()
docs_form.instance.ProductName_id = self.kwargs.get('pk')
docs_form.instance.user = self.request.user
docs_form.save()
messages.success(self.request, "Measurement Properties Updated successfully")
return HttpResponseRedirect(self.get_success_url())
def formset_invalid(self, formset):
messages.error(self.request, "Form getting invalid")
return self.render_to_response(self.get_context_data(formset=formset))
答案 0 :(得分:2)
我尚未对此进行测试,但是根据文档,可以在类级别设置与表单集相关的属性。因此,根据您的情况,添加factory_kwargs
并将can_delete
指定为True,例如:
class MeasurementPropsUpdateView(ModelFormSetView):
factory_kwargs = { 'can_order': False, 'can_delete': True}
答案 1 :(得分:0)
formset.deleted_forms仅在调用formset.save(commit = False)后可用。
def formset_valid(self, formset):
if formset.is_valid():
instances = formset.save(commit=False)
# Delete objects
for obj in formset.deleted_forms:
obj.delete()
for obj in instances:
obj.ProductName_id = self.kwargs.get('pk')
obj = user = self.request.user
obj.save()
messages.success(self.request, "Measurement Properties Updated successfully")
return HttpResponseRedirect(self.get_success_url())
#Formset is not valid
return False