views:

154

answers:

2

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?

+1  A: 

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.

John Keyes
+1  A: 
from django.utils.encoding import smart_str
...

 response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(filename)
slav0nic
but not all utf symbols can be converted ;)
slav0nic