获取django中多个复选框的值

use*_*942 3 python django excel django-views

我有一个表格,其中显示了不同客户的不同账单:

在此处输入图片说明

我的views.py中有这个代码:

@login_required
def descarga(request,id_factura):
    selected_values = request.POST.getlist('factura')
    if request.method == 'POST':
        form = Factura.objects.filter(id__in=selected_values)
        if form:

                (...Styling of the Excell file...)

         # write the header
            header = ['Cliente', 'Fecha de Factura', 'Tipo de Factura', 'Numero de Factura', 'Descripcion', 'Subtotal', 'IVA', 'Precio']

            for hcol, hcol_data in enumerate(header): # [(0,'Header 1'), (1, 'Header 2'), (2,'Header 3'), (3,'Header 4')]
            sheet.write(0, hcol, hcol_data, font_size_style)

            for facturas in form:
                 data = {
                     "Cliente": form.nombre_cliente,
                     "Fecha de Factura":form.fecha_factura,
                     "Tipo de Factura": form.tipo_Factura,
                     "Numero de Factura": form.numero_De_Factura,
                     "Descripcion": form.descripcion,
                     "Subtotal": form.importe_sin_iva,
                     "IVA": form.iva,
                     "Precio": form.importe_Total,
                     }

            for column, key in enumerate(header, start=1):
                sheet.write(1, column, str(data[key]), body_style)

            response = HttpResponse(mimetype='application/vnd.ms-excel')
            response['Content-Disposition'] = 'attachment; filename=report.xls'
            response = render_to_response(context_instance = RequestContext(request, locals()), mimetype='application/vnd.ms-excel')
            return response
Run Code Online (Sandbox Code Playgroud)

该函数将一张账单的信息下载到一个 Excel 文件中。此功能附加到不在表的同一模板中的按钮上,它在显示帐单信息的模板中(通过单击“Ver”,另一个模板以漂亮的格式显示信息)

所以现在我要做的是将按钮放在表格所在的同一页面中,并仅导出复选框中选中的按钮。

问题是:我如何告诉视图只导出被检查的那些?并且这个功能是否会以同样的方式工作,因为它在我只显示一张账单的信息的情况下工作。

这是我的模板中的代码:

{% for factura in facturas %}
   <tr>
       <td><i class="fa fa-file"> <a href="{% url 'ver_Factura' factura.pk %}">Ver</a></i>
       <div class="checkbox">
           <label>
                  <input type="checkbox">
           </label>
       </div>
       </td>
       <td>{{ factura.nombre_cliente }}</td>
       <td>{{factura.numero_De_Factura }}</td>
       <td>{{factura.fecha_factura }}</td>
                            </tr>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

任何小帮助将不胜感激。谢谢

Dan*_*man 11

在 HTML 中,每个表单字段都需要一个name属性才能提交给后端。但是对于复选框,您可以为它们提供相同的名称 - 但不同的值 - 以便它们将作为列表提交。所以你可以在你的模板中做到这一点:

<input type="checkbox" name="factura" value="{{ faktura.pk }}">
Run Code Online (Sandbox Code Playgroud)

并在视图中:

selected_values = request.POST.getlist('factura')
Run Code Online (Sandbox Code Playgroud)

这将为您提供所选 Factura ID 的列表。