Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
913 views
in Technique[技术] by (71.8m points)

python - Deleting form from django formset

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

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>')
    });

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)

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).

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...