Django - 'QuerySet' 对象没有该属性
我希望有人能帮我解决这个问题。我有一个表单,里面有一个表格。在这个表格中,每一行都有复选框,用户可以选择要导出到Excel文件的文档。这是我的HTML代码:
<tbody>
{% 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" name="factura" value="{{ factura.pk }}">
</label>
</div>
</td>
<td>{{ factura.nombre_cliente }}</td>
<td>{{factura.numero_De_Factura }}</td>
<td>{{factura.fecha_factura }}</td>
</tr>
{% endfor %}
</tbody>
我在views.py中有这个导出功能的代码:
def descarga(request):
selected_values = request.POST.getlist('factura')
if request.method == 'POST':
form = Factura.objects.filter(id__in=selected_values)
**print form**
if form:
book = xlwt.Workbook(encoding='utf8')
sheet = book.add_sheet('report')
sheet.col(0).width = int(13*380)
sheet.col(1).width = int(13*380)
sheet.col(2).width = int(13*380)
sheet.col(3).width = int(13*380)
sheet.col(4).width = int(13*380)
sheet.col(5).width = int(13*380)
sheet.col(6).width = int(13*380)
sheet.col(7).width = int(13*380)
(...Style of the sheet here...)
(...Headers of the sheet here)
**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("facturas.html",context_instance=RequestContext(request), mimetype='application/vnd.ms-excel')
book.save(response)
return response
正如你所看到的,我在控制台打印了“form”对象,以查看它包含了什么内容(如果我只选择了表格中的两个文件),我在控制台得到了这个:
[<Factura: Andreani Logistica S.A - 2231231243>, <Factura: Pechugs LAru - 23423421>]
问题出在这部分:
**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,
}**
我遇到了这个错误:
'QuerySet' object has no attribute 'nombre_cliente'
但正如你所看到的,在querySet中有一个Factura对象,它有那个值。
有没有人能给我一点提示,告诉我该如何解决这个问题?或者指引我一个正确的方向。
任何帮助都将非常感激。谢谢!
1 个回答
3
你正在遍历表单中的发票(facturas)。如果你想获取某个发票的特定客户名称(nombre_cliente
)属性,你需要使用 facturas.nombre_cliente
,而不是 form.nombre_cliente
。