3

I'm trying to create a file dynamically in Django:

response = HttpResponse(mimetype='text/txt')
response['Content-Disposition'] = 'attachment; filename=%s' % filename # UnicodeEncodeError

response.write('text')

return response

If I hardcode the filename it works properly, but if I try to create the filename from DB data that contains non-ascii characters (like รณ) I get a UnicodeEncodeError exception. How can I use the DB filename without getting an exception?

djen
  • 515
  • 1
  • 4
  • 7
  • Does this answer your question? [How to encode UTF8 filename for HTTP headers? (Python, Django)](https://stackoverflow.com/questions/1361604/how-to-encode-utf8-filename-for-http-headers-python-django) โ€“ Boris Verkhovskiy Nov 23 '20 at 20:29

2 Answers2

4
from django.utils.encoding import smart_str
...

 response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(filename)
slav0nic
  • 3,646
  • 1
  • 21
  • 15
3

You can fix the problem on the Django side but there is no guarantee it will work in all browsers.

See the testcases at http://greenbytes.de/tech/tc2231/.

For more details on this see this question, which links to a snippet to handle most cases.

Community
  • 1
  • 1
John Keyes
  • 5,479
  • 1
  • 29
  • 48