我正在尝试用python django制作一个联系人表单,现在它工作得很好,问题是我必须等待已经发送的电子邮件才能获得Httpresponse
。
有没有办法先返回Httpresponse
,然后再发送电子邮件?
send_mail(
'Subject here',
data['comentarios'],
'myemail@gmail.com',
['myemail@gmail.com'],
fail_silently=False,
)
return HttpResponse('bien') #es menor a 7 digitos
发布于 2017-02-15 04:41:19
我假设您想让用户在单击“发送”后立即看到电子邮件已发送/请求已被处理。我建议您使用AJAX来实现您正在做的事情。
Thought
需要注意的一件事是,您可能希望使用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.'})
https://stackoverflow.com/questions/42239922
复制