Django View

CSV Download


To test this view… see Django Testing.

import csv
from django.http import HttpResponse

def _get_response(file_name):
    """Create the HttpResponse object with the appropriate CSV header."""
    response = HttpResponse(content_type="text/csv")
    response["Content-Disposition"] = 'attachment; filename="{}"'.format(
    return response

def _report(response):
    csv_writer = csv.writer(response, dialect="excel")
    csv_writer.writerow(("name", "email", "consent"))
    qs = Consent.objects.current().order_by("-date_updated", "pk")
    for x in qs:
        l = [,, x.consent_given]
    return response

def report_download(request, pk):
    today =
    consent = Consent.objects.get(pk=pk)
    file_name = "consent-{}-{}-{:02d}-{:02d}.csv".format(
        consent.slug, today.year, today.month,
    response = _get_response(file_name)
    return _report(response)