您好我正在学习python / django 如何使用pre_save
发送电子邮件通知我有一个任务表单并分配给所有用户的下拉列表。我想在分配给任务时向他们发送电子邮件
这里是views.py
class Job(models.Model):
completed = models.BooleanField(default=False)
task_name = models.CharField(max_length=80, blank=False)
description = models.CharField(max_length=80, blank=False)
is_important = models.BooleanField(default=False)
completion_date = models.DateField(blank=True, null=True)
assign_to = models.ForeignKey(User, blank=True, null=True)
comments = models.TextField(blank=True)
def __unicode__(self):
return self.task_name
models.py
send_mail(
subject = 'New task',
message = 'You have been assigned to a task',
from_email = "noreply@gmail.com",
recipient_list=[Job.assign_to.email]
)
电子邮件
angular.module('xxx').controller('xxxCtrl', ['$scope', ..., '$q', function($scope, ..., $q){
...
//every checked unchecked event in multi-checkbox trigger the change in measurement
$scope.$watch('measurement', function (newValue, oldValue) {
pendingRequests = {
primary: $q.defer(),
...: $q.defer()
};
var promises = _.map(pendingRequests, function (deferred) {
return deferred.promise;
});
$q.all(promises).then(function (results) {
$scope.data = results[0];
$window.console.log($scope.data);
});
//Here i have a $http request to server
ResultService.requestResultsOnce();
});
}])
答案 0 :(得分:1)
您可以使用django包的EmailMultiAlternatives发送电子邮件。
模块可以导入为:
from django.core.mail import EmailMultiAlternatives
然后您的发送功能可以容纳此行以发送电子邮件
msg = EmailMultiAlternatives(subject, message, from_email,recipients_list)
msg.send()
答案 1 :(得分:1)
如果你想使用pre_save
信号,你需要在信号发现的地方注册信号。
有两种方法可以使用信号中的pre_save.connect
方法或使用django.dispatch.receiver
装饰器来注册它。 Docs.
由于使用connect
适用于1.7之前的版本,我将覆盖该版本。
通过在models.py
文件中注册信号,可以发现:
from django.db.models.signals import pre_save
# The arguments this function receives are defined by the `pre_save` signal.
def send_task_email(sender, instance, raw, using, update_fields):
# The logic to send the email goes here. e.g.
return send_mail(
subject='New task',
message = 'You have been assigned to a task',
from_email = "noreply@gmail.com",
recipient_list=[instance.assign_to.email]
)
# Register the pre_save signal with the Job model.
# Please note the `dispatch_uid` kwarg to avoid signal duplication.
pre_save.connect(send_task_email, sender=Job, dispatch_uid="sending_email_uid")
作为最后一点:信号将阻止执行直到完成,发送电子邮件是一个很好的候选者,可以作为后台任务实施。