从 django 表单集中删除表单 [英] Deleting form from django formset

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

问题描述

我正在尝试实现一个 django 表单集(用户可以在其中动态添加/删除表单集中的表单).

I am trying to implement a django formset (where user may dynamically add/remove forms from formset).

我使用 JS 添加新行(使用 empty_form):

I use JS to add new rows (using empty_form):

    $("#add-item").click(function(e){
        e.preventDefault();
        var count = parseInt($('#id_form-TOTAL_FORMS').val());
        $('.invoice-items').append($('#empty_invoice_item').html().replace(/__prefix__/g, count));
        $('#id_form-TOTAL_FORMS').attr('value', count+1);
        $(".invoice-items .invoice-item .col-lg-9 .form-group:last-child").last().append('<a href="#" class="delete-item"><i class="glyphicon glyphicon-remove"></i></a>')
    });

我还使用 JS 在特定表单上设置 DELETE 标志.一切都传递给视图.

I also use JS to set DELETE flag on specific forms. Everything is passed to the view.

我的视图(部分)代码:

My view (part) code:

invoice_form = InvoiceForm()
invoice_item_helper = InvoiceItemHelper
InvoiceItemFormset = formset_factory(InvoiceItemForm, extra=0, max_num=15, validate_max=True, min_num=1, validate_min=True, can_delete=True)
formset = InvoiceItemFormset()

if request.method == 'POST':
    invoice_form = InvoiceForm(request.POST)
    formset = InvoiceItemFormset(request.POST)

问题是,django 总是显示表单集中的所有表单,即使是那些标记为删除的表单.因此,即使我的发票表单有问题并且没有验证,它也会显示带有错误消息的发票表单和所有表单(再次).

The problem is, django always displays all forms in the formset, even those marked for deletion. So, even there is something wrong in my invoice form and it doesn't validate, it will show invoice form with error message AND all forms (once again).

如何完全删除在 if request.method == 'POST': 块中标记为删除的表单?可能吗?

How can I remove completely forms which are marked for deletion in if request.method == 'POST': block? Is it possible?

推荐答案

这取决于您呈现表单的方式,但您可以检查该字段form.DELETE 在模板中,如果它已设置,呈现该表单隐藏以供显示,并且数据将被传递,直到数据被处理(当所有其他表单都有效时).它还将确保表单集的表单前缀和索引完好无损.

It's dependent on how you render the forms, but you can check the field form.DELETE in the template and if it's set, render that form hidden for display and the data will be passed along until the data is processed (when all other forms are valid). It will also make sure form prefixes and indexes for the formset is intact.

当表单集被验证时,它将忽略标记为删除的表单.formset.is_valid

When a formset is validated it will ignore forms marked for deletion. formset.is_valid

您还可以使用 deleted_forms 并可能处理它们,但您仍然必须重建整个表单集而不删除已删除的表单以维护索引和表单计数.我个人发现这样做很复杂,并且会导致复杂的代码.

You can also pick up which forms are deleted in the view using deleted_forms and perhaps process them, still you will have to rebuild the whole formset without the deleted forms to maintain indexes and the count of forms. I personally found out that doing that is complex and leads to complicated code.

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

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