且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

动态删除 Django 中的内联表单集

更新时间:2023-12-06 17:10:40

是的,可以使用几种不同的方法.

首先是复制它在 Django 管理应用程序中完成的方式,即有一个带有类似于删除?"标签的复选框.然后,当您稍后在 POST 请求中处理表单集时,您检查复选框是否为 True,如果是,则删除该记录.这可能不是您要查找的内容,因为您在问题标题中使用了动态"一词:)

因此,第二种动态方法是使用 Javascript 来隐藏"页面上已删除的记录,并将删除复选框设置为 True.然后您以与上述第一个选项相同的方式处理表单集.请参阅 django-dynamic-formset 以获取以这种方式删除表单集的代码.>

第三种动态方式是使用 Ajax,当单击删除按钮时,JS 调用删除视图来删除记录并从 HTML 中删除表单集.我无法为此提供任何示例代码,但我认为上面的第二种方法更好,因为您可以将所有身份验证和标准表单验证代码保存在一个地方.

Is it possible to have Django automatically delete formsets that are not present in the request?

So for example if I had three inline formsets represented in HTML when I loaded my edit page and I use javascript to remove two of those when the request is processes Django sees that those two forms are no longer their and deletes them.

Yes, it's possible using a few different methods.

First is to copy the way it's done in the Django admin app, which is to have a checkbox with a label similar to "Delete?". Then, when you are processing the formset later in the POST request, you check to see if the checkbox is True and if so, delete the record. This probably isn't what you are looking for though since you used the word "dynamically" in your question title :)

So a second, dynamic, method would be to use Javascript to "hide" the deleted record on the page and set the delete checkbox to True. Then you process the formset the same way as the first option above. See django-dynamic-formset for code to delete formset this way.

The third, dynamic, way would be to use Ajax and when the delete button is clicked have JS call a delete view to delete the record and also delete the formset from the HTML. I can't point you to any example code for this, but I think the second method above is better anyway because you can keep all your authentication and standard form validation code in one place.