Wednesday, June 19, 2013

Table w. Checkboxes


Django 1.4, Python 2.7


This is one of those things you know all do, but there is no clear post explaining how. Or at least I couldn't find one.

MY GOAL:


Show a table of objects, where every row has a check box, that a user can check, click submit (at the end of the table) and I will receive a list of chosen items to work with.

MY SOLUTION:

In template:
<div>
    <form method="post" action="">
        {% csrf_token %}
        <table>
            <caption><h2>Table w. Checkboxes</h2></caption>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Activate</th>
                </tr>
            </thead>
            <tbody>
                {% for o in objects %}
                    <tr>
                        <td>{{ o.name }}</td>
                        <td>
                            <input type="checkbox" name="{{ o.id }}">
                        </td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>
    <input type="submit" value="Go!">
    </form>
</div>

In views.py:
def table_w_checkboxes(request):
    if request.method == 'POST':
        for o in request.POST.iterkeys():
            print o # this is the name value of the checkbox
            # do stuff with what ever value you put in the name attr of input
            # tag
            return HttpResponseRedirect(reverse('to-where-ever'))
    else:
            objects = Model.objects.all()

    return render(request, 'table_w_checkboxes.html', {'objects': objects})

First of all, no need for a special form. I did not use any form.
Secondly, see that for loop? That's the part that matters.
request.POST.iterkeys() holds a list of all 'name' attrs of checked check boxes. Meaning, those items that were not checked will not be in this list.
In my case, name attr holds objects' id's. So, o is an id of an object that was checked. Now I can do whatever I need with it. I can do Model.objects.get(id=o), or add the object to another objects relation field - MyrelatedModel.m2mfield.add(o), for example.
Thats it! Now you can show users a table of objects to choose from and to select what they need. If you have any more questions, feel free to comment ;)

No comments:

Post a Comment