Django View

CSV Download

Tip

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(
        file_name
    )
    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.name, x.email, x.consent_given]
        csv_writer.writerow(l)
    return response


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