1

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

Daniel Ozean
  • 516
  • 1
  • 6
  • 16

2 Answers2

1

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 Thurau
  • 7,564
  • 7
  • 43
  • 80
0

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
  • 5,033
  • 19
  • 26
  • I´m sending the form target to the view that is generating the pdf and get the attachment as a response. def some_view(request): response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=somefilename.pdf' ... return response But the page won´t reload after the response is returned. – Daniel Ozean Oct 27 '10 at 07:40
  • 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 Oct 27 '10 at 08:00