Reputation: 925
I need to return a txt file as HTTPResponse in Django. The file needs to contain multiple lines generated from a list (ex. ['line one', 'line two']). If I use DTL and a template, I cannot insert any line breaks except for html-specific ones. So, my current solution is to write lines to response with csv.writer. It works, but isn't there a more elegant way to get a txt file that looks like this?
line one
line two
Update: I guess, my problem is that I need CR,LF linebreaks.
Upvotes: 2
Views: 2946
Reputation: 16671
If you have a list of strings and want to output it in a response as one string only, the easiest is to use join
:
lines = ['line one', 'line two']
response_content = '\n'.join(lines)
return HttpResponse(response_content, content_type="text/plain")
Inside a template that would be:
{% for line in mylines %}
{{ line }}
{% endfor %}
This should put each line on its own line in the output.
Upvotes: 3
Reputation: 600059
Your assertion is simply false. Django template language is in no way limited to HTML; it works just as well for any format and you can quite happily use it to generate a text file.
Upvotes: 0