我想在创建新帖子时将通知电子邮件发送到在“观察者” ManyToMany字段中定义的用户列表。
该帖子的创建没有错误,并且观察者用户列表已成功添加到该帖子中(它们出现在post_detail.html模板中),但是通知电子邮件从未发送给该观察者用户。
我认为我在下面的new_post函数中做错了事,我将此代码改编 为当用户对帖子发表评论时就可以发送电子邮件,这确实有效。任何帮助,不胜感激。
models.py(相关部分):
from django.db import models
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
from django.db.models import signals
from notification import models as notification
class Post(models.Model):
author = models.ForeignKey(User, related_name="added_posts")
observers = models.ManyToManyField(User, verbose_name=_("Observers"), related_name='observers+', blank=True, null=True)
# send notification to Post observers
def create_notice_types(app, created_models, verbosity, **kwargs):
notification.create_notice_type("new_post", "New post created", "A new post has been created")
signals.post_syncdb.connect(create_notice_types, sender=notification)
def new_post(sender, instance, created, **kwargs):
context = {
'observer': instance,
'site': Site.objects.get_current(),
}
recipients = []
pk=instance._get_pk_val()
for observer in instance.observers.all().distinct():
if observer.user not in recipients:
recipients.append(observer.user)
notification.send(recipients, 'new_post', context)
signals.post_save.connect(
new_post, sender=models.get_model(
'blog', 'Post'), dispatch_uid="pkobservers")
views.py(相关部分):
@login_required
def add(request, form_class=PostForm, template_name="blog/post_add.html"):
post_form = form_class(request)
if request.method == "POST" and post_form.is_valid():
post = post_form.save(commit=False)
post.author = request.user
post_form.save()
post_form.save_m2m()
return redirect("blog_user_post_detail",
username=request.user.username, slug=post.slug)
return render_to_response(template_name,
{"post_form": post_form}, context_instance=RequestContext(request))
开心每一天1111
相关分类