views:

43

answers:

3

I want to use the django templating system to output csv like data which looks like;

!connection%block
!dosomething
!dosomethingelse
My,Header,Row,Which,Is,Comma,Seperated
All,My,Comma,Seperated,Data
All,My,Comma,Seperated,Data
All,My,Comma,Seperated,Data
All,My,Comma,Seperated,Data
!Footerblock
!that has footer information

The actual template looks like:

!connection%special@oracleconnectionstring
id,account,product,quantity,price,date
{% for r in records %}
    {{ r.id }},{{ r.account }},{{ r.product }},{{ r.quantity }},{{ r.price }}
{% endfor %}
!endtransactions

The documentation for CSVs recommends either using the csv module or a template. My particular needs are better suited for a template because some of the model fields need some manipulation using a tag library I have created.

My view is simply

result['transactions'] = Transasctions.objects.all()
rendered = render_to_string('trans.csv', result)
response =  HttpResponse(rendered , mimetype='text/csv')

response['Content-Disposition'] = 'attachment; filename=trans.csv'
return response

However the rendered template has no way of actually outputting DOS CRLF newline characters so the entire file is one long line! There must be a way of outputting a \r\n char ...

A: 

I recommend you use the csv module. You can change and define dialects, quoting etc. If you choose template, the quoting might be a bit tricky.

As for your problem, try this:

return render_to_response('trans.csv',{'transactions': Transactions.objects.all(), "newline_char": "\n"}, mimetype='text/csv')

and in the template:

{%for row in transactions%}{{row.name_of_field1}} {{row.name_of_field2}} {{row.name_of_field3}}... {{newline_char}}{%endfor%}

dekomote
Thanks for the reply but this simply outputs a "\n" in the text file
m0nonoke
+1  A: 

Use render_to_string instead of render_to_response, and as a template use normal TXT file not html one. It will hold the data about newline chars etc.

bx2
A: 

The Django templating system doesn't remove newlines usually. Do you have {% spaceless %} in your template? If not, any newline in your trans.csv file should be output in your response. It can be tricky to get those sorts of whitespace issues correct, though, since the way your space and indent template code may not be the same as how you'd want the output spaced.

Sharing the trans.csv here would make it easier to comment on what's going on.

Ned Batchelder
There is no {% spaceless %} as the template above shows - what I have found is the output is unix newline not windows newline!
m0nonoke
Then simply add: rendered = rendered.replace("\n", "\r\n") into your view function.
Ned Batchelder