gestioCOF/events/views.py

56 lines
1.9 KiB
Python
Raw Normal View History

2019-10-05 15:58:11 +02:00
import csv
from django.contrib.auth.decorators import login_required, permission_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.utils.text import slugify
2019-10-08 23:33:46 +02:00
from events.models import Event, Registration
2019-10-05 15:58:11 +02:00
@login_required
2019-10-05 16:55:05 +02:00
@permission_required("events.view_event", raise_exception=True)
2019-10-05 15:58:11 +02:00
def participants_csv(request, event_id):
event = get_object_or_404(Event, id=event_id)
# Create a CSV response
2019-10-05 15:58:11 +02:00
filename = "{}-participants.csv".format(slugify(event.title))
response = HttpResponse(content_type="text/csv")
response["Content-Disposition"] = 'attachment; filename="{}"'.format(filename)
writer = csv.writer(response)
# The first line of the file is a header
header = ["username", "email", "prénom", "nom de famille"]
options_names = list(event.options.values_list("name", flat=True).order_by("id"))
header += options_names
extra_fields = list(
event.extra_fields.values_list("name", flat=True).order_by("id")
)
header += extra_fields
writer.writerow(header)
# Next, one line by registered user
registrations = Registration.objects.filter(event=event)
for registration in registrations:
user = registration.user
row = [user.username, user.email, user.first_name, user.last_name]
# Options
2019-12-22 23:08:27 +01:00
all_choices = registration.options_choices.values_list("choice", flat=True)
options_choices = [
" & ".join(all_choices.filter(option__id=id))
for id in event.options.values_list("id", flat=True).order_by("id")
2019-12-22 23:08:27 +01:00
]
row += options_choices
# Extra info
extra_info = list(
registration.extra_info.values_list("content", flat=True).order_by(
"field__id"
)
)
row += extra_info
writer.writerow(row)
2019-10-05 15:58:11 +02:00
return response