如何制作复选框的表单处理程序,Python,Django

How to make form handler of checkbox, Python, Django

我有一个问题:我想勾选 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>

然后在 def 中我进行下一步以检查它是否有效:

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

但它不打印任何东西...我做错了什么?或者你能帮我写正确的复选框处理程序吗?

首先您应该检查 request.method == 'POST' 而不是 request.POST 中的提交按钮名称。不过,这不应该是您什么都看不到的问题。从你发布的内容来看,我不知道什么不起作用,但这里有一个例子,说明你如何实现你想要的。它假定您的模板位于 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))