我假设您想让用户在单击“发送”后立即看到电子邮件已发送/请求已得到处理。我建议你使用 AJAX 来实现你正在做的事情。
思考过程
需要注意的一点是,您可能想要show a loading gif/svg 或其他东西来表明电子邮件正在发送中。在显示加载 gif 时,继续进行表单验证:
但是,如果您想显示一条消息,例如“谢谢”,则如下所示:
在你的 JS 中应该看起来像这样(如果你使用 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
...
});
实际的 AJAX 请求:
// 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);
}
});
在你的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.'})