Matthew
Matthew

Reputation: 123

Django - Export to Excel and render to template

Changed Question: 5/5/12 2:34pm (PST)

I would like to know if it is possible to render a template from form POST data and in that template, provide a button/link to an Excel spreadsheet of the same POST data that was used in the template.

I have made an Excel download using the POST, and I have rendered a template using the POST, but I would like the following to happen with the form's Submit button is pushed: 1. Send the information from the view to template, have the template render the information, in the template have a button/link that when clicked, a window pops up asking the user if they want to Open/Save the .XLS file.

The code I am using to do each follows:
1 Render template in new URL
return render_to_response('report/result.html', {long dictionary}, context_instance=RequestContext(request))

2 Export as .XLS file using template:
response2 = render_to_response('report/result.html', {long dictionary}, context_instance=RequestContext(request))
filename = "ToolboxReport%s.xls" % (datetime.now())
response2['Content-Disposition'] = 'attachment; filename='+filename
response2['Content-Type'] = 'application/vnd.ms-excel; charset=utf-8'
return response2

Here is my intended order: 1. At Options page: select options, click Generate Report button 2. At Results page: display information, display button/link to download this info as .XLS 3. (Optional) Clicks download button: Open/Save option appears to download the same information as .XLS

I can't seem to get the POST data from the Options page to be used in both the Results page and the .XLS download.

Upvotes: 2

Views: 5894

Answers (2)

Mp0int
Mp0int

Reputation: 18727

I use two different buttons on my forms, one for listing the results and one for exporting them to excel.

In the form template:

<input type="submit" name="list" value="List Results" />
<input type="submit" name="excel" value="Export to Excel" />

And in my view function:

# process your post data here...

# end processing your post data
if request.REQUEST.get('excel'): 
    # excel button clicked
    result = '<your content result here>'
    response = http.HttpResponse(result.encode("<encoding>", 'ignore'), content_type='application/vnd.ms-excel;charset=<charset>')
    response['Content-Disposition'] = 'attachment; filename="reports.csv"'
    response['Expires'] = "Mon, 26 Jul 2013 05:00:00 GMT"
    return response
elif request.REQUEST.get('list'):
    # List button clicked
    return render_to_response(<some render param here>, <some context>, <etc>)

Upvotes: 3

Claude Vedovini
Claude Vedovini

Reputation: 2481

You just need to build a form with hidden input tags containing the information you got from the previous post and a submit button. Add an additional parameter to tell your view you want to download.

Upvotes: 1

Related Questions