I'm trying to download a a simple CSV file to get the email addresses of my users based on when they signed up. I can't seem to get the frontend ReactJS and backend Django to play nice with one another:
urls.py
...
url(r'^api/email-export/$', app.api_views.EmailExportView.as_view()),
...
api_views.py:
from rest_framework.views import APIView
class EmailExportView(APIView):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAdminUser]
def get(self, request, format=None):
user_emails = User.objects.filter(...)
response = HttpResponse(content_type="text/csv")
response["Content-Disposition"] = "attachment; filename='user_emails.csv'"
writer = csv.DictWriter(response, fieldnames=["email"])
writer.writeheader()
for email in user_emails:
writer.writerow({"email": email})
return response
and in my react file
import { AdminApiClient } from "./apiClient";
type Props = {
apiClient: AdminApiClient;
};
export function EmailExportPage({ apiClient }: Props) {
const [startDate, setStartDate] = useState(new Date());
const downloadCsv = () => {
apiClient.emailExport(startDate)
}
return (
...
<Form onSubmit={downloadCsv}>
<Button type="submit">Download</Button>
</Form>
)
apiClient.ts is a file with a helper class that performs api calls
import axios, { AxiosInstance } from "axios";
export class AdminApiClient {
apiToken: string;
client: AxiosInstance;
async emailExport(query: Date): Promise<any> {
const resp = await this.client.get("/api/email-export/", {
params: { query },
});
return resp;
}
}
When I hit the download button now, I get a weird error in the terminal:
[15/Jul/2020 17:35:16] "GET /api/email-export/?query=2020-07-15T07:34:45.691Z HTTP/1.1" 200 7
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 868, in emit
msg = self.format(record)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 741, in format
return fmt.format(record)
File "/Users/me/.local/share/virtualenvs/my-project/lib/python2.7/site-packages/django/utils/log.py", line 173, in format
if args[1][0] == '2':
IndexError: tuple index out of range
Logged from file basehttp.py, line 85