Outputting PDF with Django as attachment and reload

瘦欲@ 提交于 2019-12-08 04:52:41

问题


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


回答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).




回答2:


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.



来源:https://stackoverflow.com/questions/4030508/outputting-pdf-with-django-as-attachment-and-reload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!