动态删除 Django 中的内联表单集 [英] Dynamically Delete inline formsets in Django

查看:25
本文介绍了动态删除 Django 中的内联表单集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以让 Django 自动删除请求中不存在的表单集?

例如,如果我在加载编辑页面时用 HTML 表示了三个内联表单集,并且当请求处理时我使用 javascript 删除其中两个表单集,Django 发现这两个表单不再是他们的表单并删除它们.

解决方案

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

首先是复制它在 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.

这篇关于动态删除 Django 中的内联表单集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆