如何制作checkbox,Python,Django的表单处理程序

时间:2015-06-24 10:27:38

标签: python django checkbox django-templates

我遇到了一个问题:我想为每行表格制作复选框:

<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)

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

1 个答案:

答案 0 :(得分:1)

首先,您应该检查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))