1

I have a page that lets the viewer edit objects. The page displays a formset with one form for each object, plus one empty form should they wish to create an object, and I would like there to be a checkbox marked "Delete" under each pre-existing object (which is to say, NOT the last one because it's the extra empty form).

I added the following code to my template:

{% for form in formset %}
{{ form.as_p }}
    {% if forloop.last %}
    {% else %}
    Delete?<input type="checkbox" name="delete" value="delete"><br>
    {% endif %}
{% endfor %}

This displays the checkbox, but I don't know how to get the data about whether or not that box was checked when I am processing the form.

For background, I'm creating the formset with modelformset_factory(MyClass, extra=1) and I'm not just using can_delete because I don't want a delete checkbox to appear under my last and empty form, so I'd prefer to simply add an extra input directly in the template, if that's possible.

How would I get the data about whether or not that box has been checked?

1 Answer 1

1

As it is form, so you have got method that process it? So you can just get flag value of it with request.POST.getlist('delete')

Sign up to request clarification or add additional context in comments.

5 Comments

No, I'm afraid that doesn't work. I need to get the objects associated with each delete checkbox, but even a list of which boxes had been checked off (by order) would work. request.POST['delete'] returns a string 'delete' regardless of how many or which boxes have been checked.
Sorry, can't ask you in comments, so there was my mistake. Look at my edition: from this you will get list of all checked checkboxes. Then you must set values as objects id, so you will get list with id of checked objects.
If you go that route make sure you check the ID to make sure it's something that's actually in the formset. You could also use form numbers (forloop.counter0) then pull the associated form.instance
After @Art's first answer I changed to <input type="checkbox" name="delete" value="delete{{forloop.counter}}"><br> but found that if the first and second boxes were checked it only returned "delete2", and getlist is giving an error MultiValueDictKeyError: Key 'delete' not found in QueryDict... any suggestions?
Whoops, forgot to change my brackets to parentheses. getlist is working now, thank you very much. Just what I needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.