django download csv file using a link

前端 未结 3 1233
旧巷少年郎
旧巷少年郎 2020-12-28 09:41

I am a new to django and python. Need some guidance in this quest.

Case: When the user hits the submit button on a form, it should display Success page and a link wh

相关标签:
3条回答
  • 2020-12-28 10:34

    In the comments Ofri Raviv. you mentioned that its giving you a

    TypeError: an integer

    which is because while creating FileWrapper u are passing two parameters out of which the second one[optional] is supposed to be integer but u passed 'rb'

    wrapper = FileWrapper(file(filename),"rb")

    Which should actually be written as ('rb' is the parameter to File)

    wrapper = FileWrapper(file(filename,"rb"))

    So it was just a misalignment of braces, but makes it hard to debug sometimes.

    0 讨论(0)
  • 2020-12-28 10:38

    In your urls.py change

    urls.py url(r'^static/(?P.*)$', send_file)
    

    to

    urls.py url(r'^static/example.xls$', send_file)
    

    In the first one, you are also passing everything after the / to the view as another parameter, but your view does not accept this parameter. another option would be to accept this parameter in the view:

    def send_file(request, path):
        ...
    

    but since the path to your xls file is hard coded, I don't think you need that.

    0 讨论(0)
  • 2020-12-28 10:44

    Now it works but i had to change file extension from excel (.xls) to csv.

    My urls.py=url(r'^static/example.txt', send_file)
    My HTML link=<a href="../static/example.txt">Download CSV File</a>
    My view.py

    def send_file(request):
    
      import os, tempfile, zipfile
      from wsgiref.util import FileWrapper
      from django.conf import settings
      import mimetypes
    
      filename     = "C:\ex2.csv" # Select your file here.
      download_name ="example.csv"
      wrapper      = FileWrapper(open(filename))
      content_type = mimetypes.guess_type(filename)[0]
      response     = HttpResponse(wrapper,content_type=content_type)
      response['Content-Length']      = os.path.getsize(filename)    
      response['Content-Disposition'] = "attachment; filename=%s"%download_name
      return response
    
    0 讨论(0)
提交回复
热议问题