1

I have a view, that upn called, starts a download:

class PrintView(TemplateView): 
    template_name = "proj/listview.html"

    def get(self, request, *args, **kwargs):
        try:
            filepath = TMP.IMG()
            if os.path.exists(filepath):
                with open(filepath, 'rb') as fh:
                    response = HttpResponse(fh.read(), content_type="application/force-download")
                    response['Content-Disposition'] = 'inline; filename=' + os.path.basename(filepath)
                    messages.success(request, "image download started ...")
                    return response
            messages.error(request, "something went wrong!")
            return redirect("index")
        except Exception as e:
            messages.error(request, e)
            return redirect("index")

in my template I call a modal window with a download button, similar to:

<button id="dl_modal_submit" type="submit"</button>

which has some javascript on top:

let somvar = null;

$('#dlModal').on('show.bs.modal', function (event) {
        
    var button = $(event.relatedTarget); 
    var modal = $(this);
});

document.querySelector('#dl_modal_submit').addEventListener('click', event => {
    const params = { 
        somevar,
    }
    const paramStr = new URLSearchParams(params).toString();
    const dl= `/dl/${somevar}`;
    window.open(dl, "_self");
});

Thing is, when I click on the button I want:

  1. close the modal
  2. start the image download
  3. redirect to index

it is suggested here that I do that using two views, but surely there must be another way to do this in the javascript part?

xtlc
  • 1,070
  • 1
  • 15
  • 41
  • Also see [this answer](https://stackoverflow.com/a/48399450) which uses `window.onblur`. – djvg Nov 02 '22 at 13:25

1 Answers1

2

Absolutely!

script.js:

$('#button').click(function() {

  // close modal:
  $('#modal').hide();

  // download files:
  window.open('the_download_url', '_blank');

  // relocate:
  window.location = 'the_redirect_url';  

});
Daniel
  • 3,228
  • 1
  • 7
  • 23