我有一个问题:我想对表格的每一行进行复选框:

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

关于python - 如何制作复选框,Python,Django的表单处理程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31024171/

10-16 07:28
查看更多