views:

36

answers:

2

Hi there,

I´m using django to generate a pdf and return the response as an attachment in the view.

response = HttpResponse(mimetype='application/pdf')
response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'

Similar to the way described in the doc (http://docs.djangoproject.com/en/dev/howto/outputting-pdf/#write-your-view)

What is the best way to reload the page?

This didn´t work out (the form triggers the pdf generation):

$('#the_form').submit(function(){
  location.reload();
});

Thanks a lot, Danny

A: 

Don't reload. Instead create a view which is the target of the form. The view generates the PDF in a directory that is delivered from the real web server and then sends the user to the appropriated URL, where he can download the file (use HttpResponseRedirect).

Martin
Thanks Martin. This is a good alternative. Is it still possible to return the PDF as attachment?
Daniel Ozean
I decided to implement the approach suggested by Martin.Thank you.
Daniel Ozean
A: 

Just set the forms target to the view that generates the pdf. Below I included some pros and cons for this approach vs the approach suggested by Martin (to write files to a directory the world can read)

Pros:

  • You can do authentication or special billing or whatever
  • Every request will generate a new PDF (unless you explicitly cache it)

Cons:

  • Every request will generate a new PDF
  • Memory usage
  • You have to stream a file from Django

--

Another solution would be to use the X-SendFile header of your webserver. Do a google search for instructions for your particular server. The general idea is that your view gives the webserver a path to a file which the webserver will then read directly from disk and return to the user. You can probably "force download" even these files, have a look at the documentation for your webserver on how to do it.

knutin
I´m sending the form target to the view that is generating the pdf and get the attachment as a response.<code>def some_view(request): response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=somefilename.pdf' ... return response</code>But the page won´t reload after the response is returned.
Daniel Ozean
Aha. I see. Well, when you do stuff on form submit with javascript, that will run before the form is actually submitted, so you cannot do any reloading or redirects there. The easiest solution I can come up with is to call window.setTimeout(function() { window.location = '/your/url/' }, timeout_in_milliseconds) in the submit handler, but it is really a rather ugly hack.
knutin