Newer
Older
# coding=utf-8
import csv
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from notifications import get_today_midnight_date
from . import e500_error, wrap_response
from ..models import Subject, Appointment
@login_required
def export_to_csv(request, data_type="subjects"):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="' + data_type + '-' + get_today_midnight_date().strftime(
if data_type == "subjects":
data = get_subjects_as_array()
elif data_type == "appointments":
data = get_appointments_as_array()
writer = csv.writer(response, quotechar=str(u'"'), quoting=csv.QUOTE_ALL)
for row in data:
writer.writerow(row)
subject_fields = []
for field in Subject._meta.fields:
if field.name != "ID":
subject_fields.append(field)
field_names = []
for field in subject_fields:
field_names.append(field.verbose_name)
subjects = Subject.objects.order_by('-last_name')
for subject in subjects:
row = []
for field in subject_fields:
row.append(getattr(subject, field.name))
result.append([unicode(s).replace("\n", ";").replace("\r", ";").encode("utf-8") for s in row])
return result
appointments_fields = []
for field in Appointment._meta.fields:
if field.name != "visit" and field.name != "id" and \
field.name != "worker_assigned" and field.name != "appointment_types" and \
field.name != "room" and field.name != "flying_team":
appointments_fields.append(field)
field_names = ['ND number', 'Family name', 'Name', 'Visit']
for field in appointments_fields:
field_names.append(field.verbose_name)
appointments = Appointment.objects.order_by('-datetime_when')
for appointment in appointments:
row = [appointment.visit.subject.nd_number, appointment.visit.subject.last_name,
appointment.visit.subject.first_name, appointment.visit.follow_up_title()]
for field in appointments_fields:
row.append(getattr(appointment, field.name))
type_string = ""
for appointment_type in appointment.appointment_types.all():
type_string += appointment_type.code + ","
result.append([unicode(s).replace("\n", ";").replace("\r", ";").encode("utf-8") for s in row])
return result
def export(request):
return wrap_response(request, 'export/index.html', {})