1

A method that is recommended by most of people:

files_form_checked_chkbox = request.POST.getlist("file_of_chkbox")
for every_file in files_form_checked_chkbox:
    #do somethig

This is B method that I find:

keys = request.POST.keys()
for key in keys:
    if key != "csrfmiddlewaretoken":
        #do somethig

This is my template:

<p>List</p>
<form action="..." method="post">
    {% csrf_token %}
    {% for key in keys %}
    <p>
        <input type="checkbox" name="file_of_chkbox" value="{{key}}">
        <a href="..." >{{key}}</a>
    </p>
    {% endfor %}
    <input type="submit" value="Delete files" />
</form>

Both methods can do same thing.

I see. It's sure that A is better than B and A is explained many time. I use request

But I want to understand why B is't recommended with reson.

2 Answers 2

1

B is not doing the same thing as A.

While looping over request.POST.keys() you are doing a lot of extra work by getting the POST parameters you don't even need.

First option is doing exactly what you need to do - get the list of checkbox values. And it is readable.

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

1 Comment

If both method compare performance and readability, it's sure that A is better than B. Do you have any explanation?
0

I prefer the B method, this one implements the "Synchronizer token pattern" to prevent Cross-site request forgery vulnerability

Learn more about CSRF:

http://en.wikipedia.org/wiki/Cross-site_request_forgery

https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet

1 Comment

Do you have a specific example with django?

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.