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

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

问题描述

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



所以例如,如果我加载了三个在HTML中表示的内联表单我的编辑页面,我使用javascript删除其中的两个当请求是进程Django看到这两个形式不再是它们并删除它们。

解决方案

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



首先是复制Django管理应用程序的方式,复选框具有类似于删除的标签。然后,当您在POST请求中稍后处理表单时,请检查该复选框是否为True,如果是,则删除该记录。这可能不是你正在寻找的,因为你在你的问题标题中使用了动态这个词:)



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

第三个动态方式是使用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天全站免登陆