tags:

views:

344

answers:

2

In a django app, i need to show the result of a search, and let the user downloading a csv file of the result.
Actually i just wrote a view that take the form args to make the query via the ORM and present the result in a Table in the template.

here the end of the view:

return render_to_response(template, {'form': form, 'object_list': object_list}, context_instance=RequestContext(request))

I would like to add a link below the Table that download the csv file of the result presented. I know how to make a csv file in python/django but not how to present it in the same time than a result in the template.

Any idea?? Thanks by advance for any answer.

+6  A: 

My suggestion is to create a new entry in urls.py for the csv download link and connect it to a view that returns the csv.

Then in the template for the search results you can link to this new url, passing through the same search terms as GET parameters that you can use in the CSV view to generate the result again.

To reduce duplication, as you now have the normal html view and the csv view processing returning the same data, you can create a single view with an argument that specifies if it should return a rendered template, or a CSV result.

You mention you already know how to do this, but in case someone else stumbles on to this page, here is how a view can return CSV and make the browser download it as a file:

def csv_list(request):
    """ Renders a csv list  """
    response = HttpResponse(mimetype='text/csv')
    response['Content-Disposition'] = 'attachment; filename=file.csv'

    writer = csv.writer(response, dialect=csv.excel)
    writer.writerow(['col1', 'col2', 'col3'])
    return response
Andre Miller
thanks for the answer, i'm gonna try that as soon as possible.
Jérôme Pigeot
A: 

If the user has already filled a form with the parameters for the query you'll need to feed those parameters again to the view tha renders the CSV file. For that you could use hidden fields in a form in your template and have a submit button resend that params to the proper view.

If you want the link to the CSV to be a simple GET you'll have to generate the link dinamically passing all of those parameters in the query string. If the parameters aren't too many maybe you can use a custom URLconf with those parameters in the URL. In this last case maybe an independent view to render the CSV would work better so you don't have too many params defaulting to None in the view when rendering HTML.

gnrfan
you're right : the search form is composed of 9 fields actually so it will be a bit ugly to pass all the arguments in the url...have you already done a thing like that in an app?? thanks
Jérôme Pigeot