1

I'm defining a custom admin action called Download CSV. In this action I want to download a .csv file and show a message to the user. I have not been able to make both happen.

I tried this way:

@admin.action(description=gettext_lazy("Download CSV"))
def download_csv(self, request, queryset):
    self.message_user(request=request, message=gettext_lazy("Downloaded"))

    return self.create_csv()

@staticmethod
def create_csv() -> HttpResponse:
    headers = {'Content-Disposition': f'attachment; filename="download.csv"'}
    response = HttpResponse(content_type='text/csv', headers=headers)
    response.write(codecs.BOM_UTF8)
    csv.writer(response).writerows([['example']])
    return response

actions = [download_csv]

Does anyone know how to do it correctly?

Thanks.

  • An action does *not* return a HTTP response, that simply does something, and the modeladmin will trigger a redirect to the same page. – Willem Van Onsem Jan 02 '23 at 10:50

0 Answers0