Django template CSS – Display rows with alternate colors

Here’s a snippet to print rows in Django template with alternate colors. Assume you have 2 CSS styles for rows:

.row1 {
    background: #EDF3FE;
}
.row2 {
    background: white;
}

Template code:

{% for row in dataset %}
	<tr class="{% cycle "row1" "row2" %}">
		<td>{{row.customer}}</td>
		<td>{{row.sfid}}</td>
		<td>{{row.package}}</td>
		<td>{{row.support_expires}}</td>
	</tr>
{% endfor %}

Django – Export CSV report

Exporting CSV in Django would require changes in the view and template:

Template Code below, where hostedCustReport is the name of the view where the POST will be made

<button onclick="window.location='{% url hostedCustReport %}?export=true'" title="Export to CSV" class="button">
Export to CSV
</button>

View code – A separate section that checks for incoming GET protocol to return a CSV file. Otherwise, the normal flow to invoke the template with the locals that will be used to print the report on screen.

if request.GET.get('export', ''): #need tu data as well
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=hostedCustomerReport.csv'
    writer = csv.writer(response)
    writer.writerow(('Customer','SFID','Package','Support Expires'))
    for row in dataset:
        writer.writerow( (row['customer'], row['sfid'], row['package'], row['support_expires']) )
    return response

return render_to_response('reports/hosted_customer_report.html', locals(), context_instance=RequestContext(request))