1

I have a problem: I want to make checkboxes of each line of table:

<form action="" method="post">
    {% csrf_token %}
    <table>
        <thead>
            <tr>
                <th>cb</th>
                <th width="150">first_col</th>
                <th>sec_col</th>
                <th width="150">third_col</th>
            </tr>
        </thead>
        <tbody>
{% for i in list %}
<tr>
    <td><input type="checkbox" name="choices" value="{{i.id}}"></td>
    <td>{{ i.created_date}}</td>
    <td><a href="/{{i}}/"> {{ host }}/{{i}}/ </a></td>
    <td>{{i.number_of_clicks}}</td>
</tr>
{% endfor %}
         </tbody>
         </table>
    <button type="submit" name="delete" class="button">Del</button>
</form>

And in the def I make next in order to check if it works:

if 'delete' in request.POST:
    for item in request.POST.getlist('choices'):
        print (item)

But it does not print anything... What do i do wrong? Or can you help me to write correct handler of checkboxes?

1 Answer 1

1

First you should check for request.method == 'POST' rather than for the submit button name in request.POST. Though, that shouldn't be the problem why you don't see anything. From what you posted I don't know what's not working but here's an example that shows how you could achive what you want. It assumes your template is in test.html:

# This is just a dummy definition for the type of items you have
# in your list in you use in the template
import collections
Foo = collections.namedtuple('Foo', ['id', 'created_date', 'number_of_clicks'])

def test(request):
    # check if form data is posted
    if request.method == 'POST':
        # simply return a string that shows the IDs of selected items
        return http.HttpResponse('<br />'.join(request.POST.getlist('choices')))

    else:
        items = [Foo(1,1,1),
                 Foo(2,2,2),
                 Foo(3,3,3)]

        t = loader.get_template('test.html')
        c = RequestContext(request, {
            'list': items,
            'host': 'me.com',
            })

    return http.HttpResponse(t.render(c))
Sign up to request clarification or add additional context in comments.

2 Comments

The OP is testing for the presence of the delete key in request.POST, not for the value - so the fact that the value might be empty is irrelevant.
Oh, thanks... I only wanted make sure that request POST have I needed elements.. It has! It works well!

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.