65 lines
2.4 KiB
Python
65 lines
2.4 KiB
Python
def export_voters_csv(request):
|
|
"""
|
|
Exports selected or filtered voters to a CSV file.
|
|
"""
|
|
selected_tenant_id = request.session.get("tenant_id")
|
|
if not selected_tenant_id:
|
|
messages.warning(request, "Please select a campaign first.")
|
|
return redirect("index")
|
|
|
|
tenant = get_object_or_404(Tenant, id=selected_tenant_id)
|
|
|
|
if request.method != 'POST':
|
|
return redirect('voter_advanced_search')
|
|
|
|
action = request.POST.get('action')
|
|
select_all_results = request.POST.get('select_all_results') == 'true' or action == 'export_all'
|
|
|
|
if select_all_results:
|
|
voters, _ = get_filtered_voter_queryset(request, tenant, data_source='POST')
|
|
else:
|
|
voter_ids = request.POST.getlist('selected_voters')
|
|
voters = Voter.objects.filter(tenant=tenant, id__in=voter_ids, is_inactive=False)
|
|
|
|
voters = voters.order_by('last_name', 'first_name')
|
|
|
|
response = HttpResponse(content_type='text/csv')
|
|
response['Content-Disposition'] = f'attachment; filename="voters_export_{timezone.now().strftime("%Y%m%d_%H%M%S")}.csv"'
|
|
|
|
writer = csv.writer(response)
|
|
writer.writerow([
|
|
'Voter ID', 'First Name', 'Last Name', 'Nickname', 'Birthdate',
|
|
'Address', 'City', 'State', 'Zip Code', 'Neighborhood', 'Phone', 'Phone Type', 'Secondary Phone', 'Secondary Phone Type', 'Email',
|
|
'District', 'Precinct', 'Is Targeted', 'Voted', 'Support', 'Yard Sign', 'Window Sticker', 'Call Queue Status', 'Notes'
|
|
])
|
|
|
|
for voter in voters:
|
|
writer.writerow([
|
|
voter.voter_id,
|
|
voter.first_name,
|
|
voter.last_name,
|
|
voter.nickname,
|
|
voter.birthdate.strftime('%Y-%m-%d') if voter.birthdate else '',
|
|
voter.address,
|
|
voter.city,
|
|
voter.state,
|
|
voter.zip_code,
|
|
voter.neighborhood,
|
|
voter.phone,
|
|
voter.get_phone_type_display(),
|
|
voter.secondary_phone,
|
|
voter.get_secondary_phone_type_display(),
|
|
voter.email,
|
|
voter.district,
|
|
voter.precinct,
|
|
'Yes' if voter.is_targeted else 'No',
|
|
'Yes' if voter.voted else 'No',
|
|
voter.get_candidate_support_display(),
|
|
voter.get_yard_sign_display(),
|
|
voter.get_window_sticker_display(),
|
|
voter.get_call_queue_status_display(),
|
|
voter.notes
|
|
])
|
|
|
|
return response
|