On Fri, Dec 9, 2011 at 4:12 PM, Sells, Fred <fred.se...@adventistcare.org> wrote: > I'm getting an http request from another server in our system and I need > to respond using a csv format. I've seen the example in the docs where > the template looks like this: > > {% for row in data %}"{{ row.0|addslashes }}", "{{ row.1|addslashes }}", > "{{ row.2|addslashes }}", "{{ row.3|addslashes }}", "{{ row.4|addslashes > }}" > {% endfor %} > > > However I would like my template to work with a variable number of > fields. Short of doing a ",".join(arow) in my view, I'm not sure how > to do this without getting a trailing "," in my output. My view > snippet looks like this: > ================================================================ > results = [ (s.a, s.b, s.c, s.d, s.e) for s in today] > return render_to_response('tuples2csv.txt',{'records': results}, > mimetype='text/plain', context_instance=RequestContext(request)) > ================================================================ > > My template looks like this at this time: > =============================================================== > {% for row in records %}{% for value in row %}{{value}},{% endfor %} > {% endfor %} > =============================================================== > > The data looks like this - I've deleted much of the internal field > content since it is proprietary information > ==================================================== > 7:55,xxxx,xxxx, > 8:55,xxxx,xxxx, > 11:25,xxxx,xxxx, > 8:25,xxxx,xxxxxxx, > ============================================================= > I guess I can always convert this to a text block in my view and respond > with that, but it seems like I should be able to use the template system > for a more generic solution. I've done a fair amount of googling on > this but keep getting to the same examples that are close but not quite > what I need. > > If someone can clarify how to eliminate the trailing ","I would really > appreciate it. > > Thanks, > Fred. >
Do you have a really good reason for generating CSV in a template? It will be astonishingly slow. The python csv module simply requires a file like object to write to. A HttpResponse is a file like object. To answer your question, in a for loop there are various counters available, one of which is forloop.last, which is true the last time through the loop. https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#for Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.