Skip to content

Commit

Permalink
Export - Add CSV options, for mailipy
Browse files Browse the repository at this point in the history
  • Loading branch information
wil93 committed Dec 2, 2023
1 parent 9982077 commit 00536e3
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
5 changes: 5 additions & 0 deletions teams/templates/teams/export_data.html
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ <h1>Export data</h1>
<input type="hidden" name="key" value="accounts">
<input type=submit value="accounts.json">
</form>
<form method=post>
{% csrf_token %}
<input type="hidden" name="key" value="accounts-csv">
<input type=submit value="accounts.csv">
</form>
</div>
</div>
{% endblock %}
28 changes: 24 additions & 4 deletions teams/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import csv
import io
import json

from allauth.account.models import EmailAddress
from django import forms
from django.conf import settings
from django.contrib import messages
Expand Down Expand Up @@ -328,6 +331,16 @@ def download_json_as_file(data, filename):
response['Content-Disposition'] = f'attachment; filename={filename}'
return response

def download_csv_as_file(data, filename):
output = io.StringIO()
fieldnames = ['username', 'password', 'email']
writer = csv.DictWriter(output, fieldnames=fieldnames, extrasaction='ignore')
writer.writeheader()
writer.writerows(data)
response = HttpResponse(output.getvalue())
response['Content-Disposition'] = f'attachment; filename={filename}'
return response

@staff_member_required
@user_passes_test(lambda u: u.is_superuser, login_url='/')
def export_data(request):
Expand Down Expand Up @@ -395,12 +408,12 @@ def export_data(request):

return download_json_as_file(teams, 'teams.json')

elif key == 'accounts':
elif key == 'accounts' or key == 'accounts-csv':
accounts = []

for user in User.objects.all():
if not user.is_verified or user.is_staff:
continue
# if not user.is_verified or user.is_staff:
# continue

user_id = f"itacpc-user-{user.id}"

Expand All @@ -412,16 +425,23 @@ def export_data(request):
"password": get_random_string(8),
}
user.save()

user_emails = map(str, EmailAddress.objects.filter(verified=True, user=user).all())

accounts.append({
"id": user_id,
"username": user.credentials['username'],
"password": user.credentials['password'],
"email": ",".join(user_emails),
"type": "team",
"name": user.full_name,
"team_id": f"itacpc-team-{user.team.id}" if user.team else f"itacpc-single-{user.id}",
})
return download_json_as_file(accounts, 'accounts.json')

if key == 'accounts-csv':
return download_csv_as_file(accounts, 'accounts.csv')
else:
return download_json_as_file(accounts, 'accounts.json')

else:
raise SuspiciousOperation('Invalid request')

0 comments on commit 00536e3

Please sign in to comment.