Search code examples
javascripthtmldjango

Button to download file and redirect to new page


How do I enable my button to download and redirect to a new page? I have tried many code combination but it just downloads and does not redirect

<div class="banner">
    <h3>Download your file:<br> {{ filename }}</h3>
    <div>
        {% csrf_token %}
        <form action="{% url 'download_pdf' %}" enctype="multipart/form-data" method="post">
            {% csrf_token %}
            <button onclick="openTab()" class="btn btn-primary w-20" id="myBtn" tabindex="4">Download PDF
            </button>
        </form>
    </div>
</div>
<script>
function openTab() {
window.open('home');
}
</script>

Solution

  • You could try something like this to ensure both downloading the file and redirecting to a new page are achieved. The button click that already triggers download and then you can register a brief delay using JavaScript to redirect to your desired page:

    <div class="banner">
        <h3>Download your file:<br> {{ filename }}</h3>
        <div>
            {% csrf_token %}
            <form id="downloadForm" action="{% url 'download_pdf' %}" enctype="multipart/form-data" method="post">
                {% csrf_token %}
                <button type="button" class="btn btn-primary w-20" id="myBtn" tabindex="4" onclick="downloadAndRedirect()">Download PDF</button>
            </form>
        </div>
    </div>
    
    <script>
    function downloadAndRedirect() {
        // Submit the form to trigger the download
        document.getElementById('downloadForm').submit();
        
        // Redirect after a short delay to allow the download to start
        setTimeout(function() {
            window.location.href = 'home'; // Change 'home' to your desired redirect URL
        }, 1000); // Adjust the delay time as necessary
    }
    </script>