'Django download links only working in new tab

This is driving me crazy, I'm developing a django app and need to provide a download link to a file located in the media folder. If I type the url in a blank tab it works fine, the file is downloaded, but if I click on the link from the website nothing happens. I realize this might be because the url to the file doesn't have the same origin that the website and from what I understood the browser won't allow the download, is this correct? Is there any way around?

url of the website (in development): http://localhost:8000/django_app/view_name
url of the file: http://localhost:8000/django_app/media/file.ext

I've tried the following html href:

href="../media/file.ext" download target="_blank"

And the following view:

def download_file(request):


fl_path = settings.MEDIA_ROOT + "\\filename.ext"
filename = "file_name"

mime_type, _ = mimetypes.guess_type(fl_path)
response = HttpResponse(fl, content_type=mime_type)
response['Content-Disposition'] = "attachment; filename=%s" % filename

return response

Nothing happens when I click on the link, no error generated. If I open the link in a new tab it downloads the file normally... Note that I need to be able to change the href link dynamically. Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source