RioAraki
RioAraki

Reputation: 554

Unable to download file in django

I'm new to django and I have developed a django website which allows people to download epub file by typing the book's name. I have checked the django api about download and the code seems to work fine (no error reported), but there is no download window pops up by my browser. I'm testing on 127.0.0.1:8000 and here is part of my code

view.py

def download(request, file_path, book_name):
    if os.path.exists(file_path):
        response = HttpResponse(content_type="application/epub+zip")
        response['X-Sendfile'] = file_path
        response['Content-Disposition'] = 'attachment; filename=abc.epub'
        print (response)
        return response
    raise False

According to my console it could find the file path, and by printing the message it shows

<HttpResponse status_code=200, "application/epub+zip">
[26/Mar/2018 18:31:03] "POST / HTTP/1.1" 200 509

Everything seems to work fine, just the download window does not pop up. Does anyone have any idea where is goes wrong? Thanks!

========== Supplementary: To give you a full sight of the view file, download is called by index and thats all:

def index(request):
    template = loader.get_template('index.html')
    book_name = ''
    result = ''
    if request.method == "POST": # check if user actually type a book name
        book_name = request.POST.get("book_name")
    cwd = os.getcwd()
    if book_name != '': # search and create are functions from other file which would create an epub file and put it in current directory
        result = search.search_ask(book_name)
        create.create(book_name)

        file_path = os.path.join(cwd, book_name) + '.epub'
        download(request, file_path, book_name)

    context = {'return_value': book_name,
               'result_1': result,
               'cwd': cwd}

    return HttpResponse(template.render(context, request))

Upvotes: 2

Views: 1368

Answers (1)

Gytree
Gytree

Reputation: 540

you don't return the response object returned by the download method. most be:

return donwload(request, file_path, book_name)

or

download_response = donwload(request, file_path, book_name)
if download_response:
    return download_response
else:
    # not found or other return.

in your code always return

return HttpResponse(template.render(context, request))

Upvotes: 1

Related Questions