Search code examples
javascriptpythonhtmldjangoform-submit

Issue with Loading HTML Template After Sending Email in Django


I'm working on a Django project where I need to send an email after a form submission. I have implemented the email sending functionality using the smtplib module. The email is sent successfully, but after that, I'm unable to load the corresponding HTML template (delivery_email_success.html).

Here's the relevant code in my view:

def enviar_email(request):
if request.method == 'POST':
    # Process data and prepare the email
    try:
        # Email setup and sending
        # ...
        server.quit()
    except smtplib.SMTPException as e:
        return render(request, 's3_error.html')
    
    print('Now rendering the success')
    return render(request, 'delivery_email_success.html')
else:
    return HttpResponse(status=405)

And here's the HTML part that submits the form and calls this function:

    const emailForm = document.getElementById('email-form');
emailForm.addEventListener('submit', (event) => {
    event.preventDefault();

    const visibleRows = document.querySelectorAll('.result-row');
    const data = [];

    visibleRows.forEach(row => {
        const rowData = {
            title: row.querySelector('td:nth-child(2)').textContent,
            catalog: row.querySelector('td:nth-child(3)').textContent,
            folder: row.querySelector('td:nth-child(4)').textContent,
            assets: row.querySelector('td:nth-child(5)').textContent,
            package: row.querySelector('td:nth-child(6)').textContent,
            sk: row.querySelector('td:nth-child(7)').textContent
        };

        data.push(rowData);
    });

    const emailBody = tinymce.activeEditor.getContent({ format: 'html' });

    const formData = new FormData();
    formData.append('email_body', emailBody);
    formData.append('data', JSON.stringify(data));

    const csrfToken = document.querySelector('input[name="csrfmiddlewaretoken"]').value;
    formData.append('csrfmiddlewaretoken', csrfToken);

    fetch("{% url 'email_delivery' %}", {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(result => {
        // Manejar la respuesta del servidor
    })
    .catch(error => {
        // Manejar errores
    });
});

I have verified that the delivery_email_success.html template exists in the correct location and that the file name is written correctly in the view. Additionally, no errors are displayed in the console or logs.

Why the template is not loading correctly after successfully sending the email? What could be causing this issue?

Thank you!


Solution

  • Ok, I figure it out...

    In the javascript code I added:

     .then(result => {
            if (result.success) {
                alert('¡El correo electrónico se ha enviado correctamente!');
                // Redirigir a la página deseada
                window.location.href = "{% url 'enviar_email' %}";
            } else {
                alert('Ha ocurrido un error al enviar el correo electrónico.');
                // Manejar el error de envío de correo
            }
        })
    

    and the views.py now is returning a success to this html like this:

    return JsonResponse({'success': True})
    

    And now is working.