1👍
I assume you want to let the user see that the email has been sent/the request has been processed immediately after clicking ‘Send’. I suggest that you use AJAX to achieve what you are doing.
Thought Process
One thing to note is that you probably want to show a loading gif/svg or something to indicate that the email is in the process of being sent. While the loading gif is shown, proceed with form validation:
-
if everything is ok: proceed with AJAX request send email and return a success/error message indicating whether email was sent.
-
if validation failed: just display error messages
However, if you want to display a message, like ‘Thank you’, it’s something like this:
It should probably look something like this in your JS (if you’re using jQuery):
$('#form').on('submit', function(e) {
e.preventDefault();
// do some validation
// if the validation deems the form to be OK - display the 'Thank you!` message first THEN proceed to AJAX request.
$('#form').append('Thank you!');
// insert AJAX here
...
// if the validation returns errors - just display errors
...
});
The actual AJAX request:
// AJAX request
$.ajax({
method: 'POST',
url: '../send_email/', # Just an example - this should be a url that handles a POST request and sends an email as a response
data: $('#form').serialize(),
success: function(response) {
// anything you want
// an example would be:
if (response.success) {
$('#form').append(response.success);
}
});
In your views.py
:
class SendEmail(View):
def post(self, request, *args, **kwargs):
if request.is_ajax():
send_mail(
'Subject here',
data['comentarios'],
'myemail@gmail.com',
['myemail@gmail.com'],
fail_silently=False,
)
return JsonResponse({'success': 'Just a JSON response to show things went ok.'})
return JsonResponse({'error': 'Oops, invalid request.'})