def ready(self): super(WorkAppConfig, self).ready() from work.models import create_unit_types, create_exchange_skills from general.models import create_general_types from work.signals import comment_notification post_migrate.connect(create_general_types, sender=self) post_migrate.connect(create_unit_types, sender=self) post_migrate.connect(create_exchange_skills, sender=self) comment_was_posted.connect(comment_notification, sender=self) #Comment)
def ready(self): super(WorkAppConfig, self).ready() from work.models import create_unit_types, create_exchange_skills from general.models import create_general_types from work.signals import comment_notification post_migrate.connect(create_general_types, sender=self) post_migrate.connect(create_unit_types, sender=self) post_migrate.connect(create_exchange_skills, sender=self) comment_was_posted.connect(comment_notification, sender=self) #Comment) #comment_will_be_posted.connect(pre_comment, sender=Comment) logger.debug("Connected signals to post_migrate and comment_was_posted")
def ready(self): super(WorkAppConfig, self).ready() from work.models import create_unit_types, create_exchange_skills, fill_empty_languages from general.models import create_general_types from work.signals import comment_notification from django.db import DEFAULT_DB_ALIAS if not settings.TESTING and is_database_synchronized(DEFAULT_DB_ALIAS): pre_migrate.connect(fill_empty_languages, sender=self) post_migrate.connect(create_general_types, sender=self) post_migrate.connect(create_unit_types, sender=self) post_migrate.connect(create_exchange_skills, sender=self) comment_was_posted.connect(comment_notification, sender=self) #Comment)
def connect_discussion_signals(): """ Connect all the signals on the Comment model to maintains a valid discussion count on each entries when an action is done with the comments. """ post_save.connect( count_discussions_handler, sender=comment_model, dispatch_uid=COMMENT_PS_COUNT_DISCUSSIONS) pre_delete.connect( count_discussions_handler, sender=comment_model, dispatch_uid=COMMENT_PD_COUNT_DISCUSSIONS) comment_was_flagged.connect( count_discussions_handler, sender=comment_model, dispatch_uid=COMMENT_WF_COUNT_DISCUSSIONS) comment_was_posted.connect( count_comments_handler, sender=comment_model, dispatch_uid=COMMENT_WP_COUNT_COMMENTS) pingback_was_posted.connect( count_pingbacks_handler, sender=comment_model, dispatch_uid=PINGBACK_WP_COUNT_PINGBACKS) trackback_was_posted.connect( count_trackbacks_handler, sender=comment_model, dispatch_uid=TRACKBACK_WP_COUNT_TRACKBACKS)
def connect_discussion_signals(): """ Connect all the signals on the Comment model to maintains a valid discussion count on each entries when an action is done with the comments. """ post_save.connect(count_discussions_handler, sender=comment_model, dispatch_uid=COMMENT_PS_COUNT_DISCUSSIONS) pre_delete.connect(count_discussions_handler, sender=comment_model, dispatch_uid=COMMENT_PD_COUNT_DISCUSSIONS) comment_was_flagged.connect(count_discussions_handler, sender=comment_model, dispatch_uid=COMMENT_WF_COUNT_DISCUSSIONS) comment_was_posted.connect(count_comments_handler, sender=comment_model, dispatch_uid=COMMENT_WP_COUNT_COMMENTS) pingback_was_posted.connect(count_pingbacks_handler, sender=comment_model, dispatch_uid=PINGBACK_WP_COUNT_PINGBACKS) trackback_was_posted.connect(count_trackbacks_handler, sender=comment_model, dispatch_uid=TRACKBACK_WP_COUNT_TRACKBACKS)
from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ if 'django_comments' in settings.INSTALLED_APPS: from django_comments.models import Comment from django_comments.signals import comment_was_posted else: from django.contrib.comments.models import Comment from django.contrib.comments.signals import comment_was_posted from satchmo_utils.signals import collect_urls import product import satchmo_store class ProductRating(models.Model): """A rating attached to a comment""" comment = models.OneToOneField(Comment, verbose_name="Rating", primary_key=True) rating = models.IntegerField(_("Rating")) import config from urls import add_product_urls, add_comment_urls collect_urls.connect(add_product_urls, sender=product) collect_urls.connect(add_comment_urls, sender=satchmo_store) from .listeners import save_rating, one_rating_per_product, check_with_akismet comment_was_posted.connect(save_rating, sender=Comment) comment_was_posted.connect(one_rating_per_product, sender=Comment) comment_was_posted.connect(check_with_akismet, sender=Comment)
# We will use the implcit id tag = models.CharField(max_length=10, unique=True) creation_date = models.DateTimeField(auto_now_add=True) class Post(models.Model): subject = models.CharField(max_length=160) content = models.CharField(max_length=800) public = models.BooleanField(default=False) post_date = models.DateTimeField(auto_now_add=True) followers = models.ManyToManyField(User, related_name='user_followers') author = models.ForeignKey(User, related_name='user_author', on_delete=models.CASCADE) tags = models.ManyToManyField(Tag, related_name="tagged") picture_link = models.CharField(max_length=150, blank=True) def get_absolute_url(self): return reverse('show-post', kwargs={'post_id': self.id}) class Notification(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) text = models.CharField(max_length=36,default="New comment on a post you follow") notif_date = models.DateTimeField(auto_now_add=True) comment_was_posted.connect(notify_followers) class PostForm(forms.ModelForm): class Meta: model = Post fields = ('subject', 'content', 'public', 'picture_link')
html = """ <html> <body> <h2>Treachery Downtime Notification</h2> <p> Hi %s! <br><br> You have recieved a new comment on one of your downtime actions. Please login and reply if needed. <br><br> <b>%s</b> commented on your action <i>%s</i>: <br><br> <div style='padding-left:10px'> %s </div> </p> </body> </html> """ % ( receipient_user.username, comment.name, target_object, comment.comment, ) send_mail("[Treachery Downtime]: New comment", "", "", [to_address], fail_silently=True, html_message=html) except: print("Error while sending mail notification: %s" % kwargs) comment_was_posted.connect(notify_user_about_comment)
from mezzanine.generic.models import ThreadedComment from sanitize import sanitize from django_comments.signals import comment_was_posted from django.utils.module_loading import import_string from django.conf import settings comment_class = import_string(settings.COMMENT_CLASS) def comment_sanitizer(sender, comment, request, **kwargs): comment.comment = sanitize(comment.comment) comment.save() # comment_will_be_posted would be better, but mezzanine does not # seem to have that hooked up # COMMENT_FILTER in your settings.py needs to be set to this function # and you need to turn off autoescapting around the output of the # comment in your templates def comment_filter(comment_text): return comment_text comment_was_posted.connect(comment_sanitizer, sender=ThreadedComment)
def get_queryset(self): return Article.objects.select_related('user').filter(slug=self.kwargs['slug']) class EditArticleView(LoginRequiredMixin, AuthorRequireMixin, UpdateView): # 注意类的继承顺序 """编辑文章""" model = Article message = "您的文章编辑成功!" form_class = ArticleForm template_name = 'articles/article_update.html' def form_valid(self, form): form.instance.user = self.request.user return super(EditArticleView, self).form_valid(form) def get_success_url(self): messages.success(self.request, self.message) return reverse('articles:list') def notify_comment(**kwargs): """文章有评论时通知作者""" actor = kwargs['request'].user obj = kwargs['comment'].content_object notification_handler(actor, obj.user, 'C', obj) # 有评论触发 comment_was_posted.connect(receiver=notify_comment)
# Comment has a parent, we'll use the _replied notices notice_type_suffix = "replied" infodict["parent_comment"] = comment.parent infodict["parent_comment_user"] = comment.parent.user # Additionnaly, we need to notify the user that posted the comment we # are replying to if comment.parent.user and comment.parent.user != comment.user: notification.send([comment.parent.user], "comment_reply_received", infodict) else: notice_type_suffix = "posted" # Notifications of stuff I'm doing notification.send([comment.user], "comment_%s" % (notice_type_suffix, ), infodict) # Notifications to my friends and/or my followers, except the author of the # parent comment, since he'll receive a separate notice anyway if friends: notification.send((x['friend'] for x in Friendship.objects.friends_for_user(comment.user) if x['friend'] != comment.parent.user), "comment_friend_%s" % (notice_type_suffix, ), infodict ) if relationships: followers = comment.user.relationships.followers() if comment.parent and comment.parent.user: followers = followers.exclude(username=comment.parent.user.username) notification.send(followers, "comment_friend_%s" % (notice_type_suffix, ), infodict) comment_was_posted.connect(comment_callback_for_notification)
import lfc.utils def comment_was_posted_listener(sender, **kwargs): """Listen to order submitted signal """ portal = lfc.utils.get_portal() site = Site.objects.get(id=settings.SITE_ID) comment = kwargs.get("comment") subject = "New Comment in %s" % portal.title from_email = portal.from_email to_emails = portal.get_notification_emails() body = "Name: %s\n" % comment.name body += "E-Mail: %s\n" % comment.email body += "URL: %s\n" % comment.url body += "Comment: \n%s\n\n\n" % comment.comment body += "Comment URL: %s" % "http://" + site.domain + "%s" % comment.content_object.get_absolute_url() mail = EmailMessage( subject=subject, body=body, from_email=from_email, to=to_emails ) mail.send(fail_silently=True) comment_was_posted.connect(comment_was_posted_listener)
from .exceptions import EmailNotificationException class Question(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=75) text = models.TextField() timestamp = models.DateTimeField(auto_now=False, auto_now_add=False) def __unicode__(self): return "%s: %s" % (self.author.username, self.title) def get_minified_text(self, max_length=100): if len(self.text) <= max_length: result = self.text else: result = self.text[:max_length] + u'...' return result def notify_author(sender, comment, request, **kwargs): question = Question.objects.get(id=comment.object_pk) try: notify(question, comment, request) except Exception as e: raise EmailNotificationException("Failed to notify author:\n%s" % str(e)) comment_was_posted.connect(notify_author, dispatch_uid='notify_author')
recipients = comment.content_object.explorers.all() elif model == 'Narrative': recipients = comment.content_object.experience.explorers.all() elif model == 'Photo': recipients.append(comment.content_object.author) for recipient in recipients: newnotify = Notification.objects.create( recipient=recipient, verb='has posted a new note', actor_content_type=ContentType.objects.get_for_model(comment.user), actor_object_id=comment.user.pk, target_content_type=comment.content_type, target_object_id=comment.object_pk, public=True, description=comment.comment, timestamp=timezone.now() ) if newnotify.recipient.notify: to = newnotify.recipient.email from_email = '*****@*****.**' subject = 'New note on your Acressity journey' text_content = render_to_string('notifications/email.txt', {'notice': newnotify, 'domain': get_site_domain()}) html_content = render_to_string('notifications/email.html', {'notice': newnotify, 'domain': get_site_domain()}) message = EmailMultiAlternatives(subject, text_content, from_email, [to]) message.attach_alternative(html_content, 'text/html') # This will no longer be necessary in Django 1.7. Can be provided to send_mail as function parameter message.send() comment_was_posted.connect(comment_handler)
comment__content_type__model='product', comment__is_public=True, rating__gt=0).distinct() class ProductRatingManager(models.Manager): def get_queryset(self): return ProductRatingQuerySet(self.model) def rated_products(self): return self.get_queryset().rated_products() class ProductRating(models.Model): """A rating attached to a comment""" comment = models.OneToOneField(Comment, verbose_name="Rating", primary_key=True, on_delete=models.CASCADE) rating = models.IntegerField(_("Rating")) objects = ProductRatingManager() from . import config from .urls import add_product_urls, add_comment_urls collect_urls.connect(add_product_urls, sender=product) collect_urls.connect(add_comment_urls, sender=satchmo_store) from .listeners import save_rating, one_rating_per_product, check_with_akismet comment_was_posted.connect(save_rating, sender=Comment) comment_was_posted.connect(one_rating_per_product, sender=Comment) comment_was_posted.connect(check_with_akismet, sender=Comment)
verb='has posted a new note', actor_content_type=ContentType.objects.get_for_model(comment.user), actor_object_id=comment.user.pk, target_content_type=comment.content_type, target_object_id=comment.object_pk, public=True, description=comment.comment, timestamp=timezone.now()) if newnotify.recipient.notify: to = newnotify.recipient.email from_email = '*****@*****.**' subject = 'New note on your Acressity journey' text_content = render_to_string('notifications/email.txt', { 'notice': newnotify, 'domain': get_site_domain() }) html_content = render_to_string('notifications/email.html', { 'notice': newnotify, 'domain': get_site_domain() }) message = EmailMultiAlternatives(subject, text_content, from_email, [to]) message.attach_alternative( html_content, 'text/html' ) # This will no longer be necessary in Django 1.7. Can be provided to send_mail as function parameter message.send() comment_was_posted.connect(comment_handler)
if (not settings.COMMENTS_XTD_CONFIRM_EMAIL or (comment.user and comment.user.is_authenticated())): if not _comment_exists(comment): new_comment = _create_comment(comment) comment.xtd_comment = new_comment notify_comment_followers(new_comment) else: ctype = request.POST["content_type"] object_pk = request.POST["object_pk"] model = models.get_model(*ctype.split(".")) target = model._default_manager.get(pk=object_pk) key = signed.dumps(comment, compress=True, extra_key=settings.COMMENTS_XTD_SALT) send_email_confirmation_request(comment, target, key) comment_was_posted.connect(on_comment_was_posted) def sent(request): comment_pk = request.GET.get("c", None) try: comment_pk = int(comment_pk) comment = XtdComment.objects.get(pk=comment_pk) except (TypeError, ValueError, XtdComment.DoesNotExist): template_arg = ["django_comments_xtd/posted.html", "comments/posted.html"] return render_to_response(template_arg, context_instance=RequestContext(request)) else: if (request.is_ajax() and comment.user and comment.user.is_authenticated()):
'domain': domain }, True) else: notification.send(other_commenters, "comment_on_commented", {'comment': comment}, True, sender=comment.user) notification.send(other_wishers, "wishlist_comment", {'comment': comment}, True, sender=comment.user) from regluit.core.tasks import emit_notifications emit_notifications.delay() comment_was_posted.connect(notify_comment) # Successful campaign signal # https://code.djangoproject.com/browser/django/tags/releases/1.3.1/django/db/models/signals.py successful_campaign = Signal(providing_args=["campaign"]) def notify_successful_campaign(campaign, **kwargs): """send notification in response to successful campaign""" logger.info('received successful_campaign signal for {0}'.format(campaign)) # supporters and staff -- though it might be annoying for staff to be getting all these notices! staff = User.objects.filter(is_staff=True) supporters = (User.objects.get(id=k) for k in campaign.supporters()) notification.send(itertools.chain(staff, supporters),
So we check to see if the user's first comment, and set the date if so. (There's a chance that the user might already have a first_comment_date which is after this Annotation's date, eg, during importing old comments. So we test for that too.) """ # So, if this annotation has a user, and is visible: if self.user is not None and self.is_public == True \ and self.is_removed == False: # And if this annotation is earlier than the user's # first_comment_date: if self.user.first_comment_date is None or \ self.submit_date < self.user.first_comment_date: self.user.first_comment_date = self.submit_date self.user.save() @receiver(signals.post_delete, sender=Annotation) def post_annotation_delete_actions(sender, instance, using, **kwargs): """ If we're deleting a comment, we need to make sure the parent object's comment count and most-recent-comment date are still accurate. """ instance.set_parent_comment_data() comment_was_posted.connect( test_comment_for_spam, sender=Annotation, dispatch_uid='comments.post_comment', )
site_name = Site.objects.get_current().name domain = kwargs['request'].get_host() try: slug = comment.content_object.project.fobi_slug if settings.PROJECTS_LOGIN: obj = settings.PROJECTS_LOGIN for pro in obj: if pro == slug: site_name = comment.content_object.project.agent.name except: pass joinrequest_url= "https://" + domain +\ "/work/project-feedback/" + str(comment.content_object.project.agent.id) +\ "/" + str(comment.content_object.id) + "/" notification.send( users, "comment_join_request", { "name": comment.name, "comment": comment.comment, "site_name": site_name, "joinrequest_url": joinrequest_url, "jn_req": comment.content_object, "current_site": kwargs['request'].get_host(), }) # Connecting signal "comment_was_posted" to comment_notification() from django_comments.models import Comment from django_comments.signals import comment_was_posted comment_was_posted.connect(comment_notification, sender=Comment)
# are replying to if comment.parent.user and comment.parent.user != comment.user: notification.send([comment.parent.user], "comment_reply_received", infodict) else: notice_type_suffix = "posted" # Notifications of stuff I'm doing notification.send([comment.user], "comment_%s" % (notice_type_suffix,), infodict) # Notifications to my friends and/or my followers, except the author of the # parent comment, since he'll receive a separate notice anyway if friends: notification.send( ( x["friend"] for x in Friendship.objects.friends_for_user(comment.user) if x["friend"] != comment.parent.user ), "comment_friend_%s" % (notice_type_suffix,), infodict, ) if relationships: followers = comment.user.relationships.followers() if comment.parent and comment.parent.user: followers = followers.exclude(username=comment.parent.user.username) notification.send(followers, "comment_friend_%s" % (notice_type_suffix,), infodict) comment_was_posted.connect(comment_callback_for_notification)
joinrequest_url= "https://" + domain +\ "/work/project-feedback/" + str(comment.content_object.project.agent.id) +\ "/" + str(comment.content_object.id) + "/" #logger.debug("Ready to send comment notification at jr_url: "+str(joinrequest_url)) notification.send( users, "comment_join_request", {"name": comment.name, "comment": comment.comment, "site_name": comment.content_object.project.agent.nick, #site_name, "joinrequest_url": joinrequest_url, "jn_req": comment.content_object, "current_site": domain, "context_agent": comment.content_object.project.agent, "request_host": domain, } ) else: logger.error("The comment is related an unknown model: "+str(ct_commented.model)) raise ValidationError("The comment is related an unknown model: "+str(ct_commented.model)) # This don't work anymore! now the connection is at work/apps.py ... but seems not enough? connect here too # Connecting signal "comment_was_posted" to comment_notification() from django_comments.models import Comment from django_comments.signals import comment_was_posted#, comment_will_be_posted comment_was_posted.connect(comment_notification, sender=Comment) logger.debug("Connect comment_was_posted signal with Comment sender")
def __str__(self): return "%s flag of comment ID %s by %s" % ( self.flag, self.comment_id, self.user.get_username() ) def save(self, *args, **kwargs): if self.flag_date is None: self.flag_date = timezone.now() super(CommentFlag, self).save(*args, **kwargs) class UserNotificationsCount(models.Model): user_id = models.IntegerField() has_readed = models.BooleanField(default=False) #unread_count = models.IntegerField(default=0) comment = models.ForeignKey(Comment, on_delete = models.CASCADE, null = True, blank = True) def __str__(self): return '<UserNotificationsCount %s: %s>' % (self.user_id, self.has_readed) def post_post_save(sender, comment, request, *args, **kwargs): post = comment if post.superior: from csinla_accounts.models import Profile su_id = Profile.objects.get(email=post.superior) event = UserNotificationsCount(user_id=su_id.id, comment = post) event.save() event = UserNotificationsCount(user_id=post.content_object.author.id, comment = post) event.save() comment_was_posted.connect(post_post_save)
def get_success_url(self): #通过get_object()获取对象 return reverse_lazy('article:detail', args=[self.get_object().id]) class ArticleDrafts(LoginRequiredMixin, ListView): """ 草稿箱 """ model = Article template_name = 'article/drafts.html' context_object_name = 'article_list' paginate_by = 4 def get_queryset(self): article_list = Article.objects.filter(status='0', user=self.request.user) return article_list def comment_signal(**kwargs): """信号函数""" sender = kwargs['request'].user instance = kwargs['comment'].content_object post_notice(sender, instance.user, 'R', instance) # https://django-contrib-comments.readthedocs.io/en/latest/signals.html#comment-was-posted comment_was_posted.connect(receiver=comment_signal) # django-comment-signal;
def appendUser(u): if u not in users and u.profile.receive_email and u.is_active: users.append(u) if comment.user.id is not obj.author.id: appendUser(obj.author) for c in comments: appendUser(c.user) pprint.pprint(users) notification.send(users, 'comment_posted', data) # connect signal comment_was_posted.connect(send_comment_notification) @receiver(post_save, sender=Note) def send_post_notification(sender, **kwargs): # no point in proceeding if notification is not available if not notification: return note = kwargs['instance'] data = { 'note': note, } users = User.objects.filter(is_active=True, profile__receive_email=True).exclude(id=note.author.id)
if ctype.name and ctype.name == u'software': subject = 'New comment on mloss.org software project ' + sw.title message = '''Dear mloss.org user, you are receiving this email as you have subscribed to the "''' message += sw.title message += '''" software project, for which a new comment has just been posted. Feel free to visit mloss.org to see what has changed. ''' else: return # no comment notification for objects other than software yet message += 'http://%s%s' % (Site.objects.get_current().domain, comment.get_absolute_url()) message += ''' Friendly, your mloss.org team. ''' send_mails(subscribers, subject, message) except ObjectDoesNotExist: pass comment_was_posted.connect(comment_notification)
# pk、slug均为默认的,不需要手动定义 class ArticleEditView(LoginRequiredMixin, AuthorRequiredMixin, UpdateView): # 注意类的继承顺序 """编辑文章""" model = Article form_class = ArticleForm template_name = "article/article_update.html" def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) def get_success_url(self): """编辑成功后跳转""" message = "文章编辑成功!" messages.success(self.request, message) return reverse_lazy("article:article", kwargs={"slug":self.get_object().slug}) def notify_comment(**kwargs): """文章有评论时候通知作者""" from django_comments.models import Comment actor = kwargs["request"].user obj = kwargs["comment"].content_object # 评论的实体对象(实现由外键关联) notification_handler(actor, obj.user, "C", obj) # 观察者模式 = 订阅[列表] + 通知(同步) comment_was_posted.connect(receiver=notify_comment) # 评论后连接到notify_comment这个目标,由目标函数来处理
from django.contrib import messages from django.utils.translation import ugettext_lazy as _ from django_comments.signals import comment_was_posted def thank_user(sender, comment=None, request=None, **kwargs): messages.add_message(request, messages.SUCCESS, _('You comment has been posted!')) comment_was_posted.connect(thank_user)
import lfc.utils def comment_was_posted_listener(sender, **kwargs): """Listen to order submitted signal """ portal = lfc.utils.get_portal() site = Site.objects.get(id=settings.SITE_ID) comment = kwargs.get("comment") subject = "New Comment in %s" % portal.title from_email = portal.from_email to_emails = portal.get_notification_emails() body = "Name: %s\n" % comment.name body += "E-Mail: %s\n" % comment.email body += "URL: %s\n" % comment.url body += "Comment: \n%s\n\n\n" % comment.comment body += "Comment URL: %s" % "http://" + site.domain + "%s" % comment.content_object.get_absolute_url( ) mail = EmailMessage(subject=subject, body=body, from_email=from_email, to=to_emails) mail.send(fail_silently=True) comment_was_posted.connect(comment_was_posted_listener)
"""用户更新文章""" model = Article form_class = ArticleForm template_name_suffix = '_update_form' template_name = "blogs/article_update_form.html" def get_success_url(self): message = "您的文章已更新成功!" # Django框架中的消息闪现机制 messages.success(self.request, message) # 消息传递给下一次请求 return reverse_lazy('blogs:detail', kwargs={'slug': self.get_object().slug}) def form_valid(self, form): form.instance.user = self.request.user return super(ArticleUpdateView, self).form_valid(form) # success_url = reverse_lazy('blogs:list') def comment_notify(**kwargs): """文章有评论时通知作者""" actor = kwargs['request'].user action_object = kwargs['comment'].content_object notification_handler(actor, action_object.user, 'C', action_object) # # 观察者模式: 订阅[列表] + 通知(同步) comment_was_posted.connect(receiver=comment_notify)
model = Article form_class = ArticleForm template_name_suffix = '_update_form' template_name = "blogs/article_update_form.html" def form_valid(self, form): form.instance.user = self.request.user return super(ArticleUpdateView, self).form_valid(form) # success_url = reverse_lazy('blogs:list') def get_success_url(self): message = "您的文章已更新成功!" # Django框架中的消息闪现机制 messages.success(self.request, message) # 消息传递给下一次请求 return reverse_lazy('blogs:detail', kwargs={'slug': self.get_object().slug}) # 传入路由的关键字参数 def notify_comment(**kwargs): """文章有评论时通知作者""" actor = kwargs['request'].user # 动作的执行者 obj = kwargs['comment'].content_object # 动作的对象 notification_handler(actor, obj.user, 'C', obj) comment_was_posted.connect(receiver=notify_comment) # 评论被提交后执行notify_comment # from django_comments.models import Comment # Comment
def get_display_name(instance, classname): if classname == 'Doc': return 'Document' elif classname == 'Post': return instance.type.capitalize() else: return classname # These are all the receivers for the various signals. We could do this with a @receiver before each function as well # Note: must use a unique string for "dispatch_id" to prevent functions from being called again every time the # module is imported # post_save.connect(log_instance_event, sender=Post, dispatch_uid="log_post_event") post_save.connect(log_instance_event, sender=Doc, dispatch_uid="log_doc_event") post_save.connect(log_instance_event, sender=News, dispatch_uid="log_news_event") comment_was_posted.connect(log_comment_event, dispatch_uid="log_comment_event") # callback receiver function for Post update events @receiver(post_signal) def post_signal_receiver(sender, **kwargs): instance = sender signal_type = kwargs['signal_type'] project = instance.project user = instance.author classname = instance.__class__.__name__ if signal_type == SIGNAL_OBJECT_CREATED: title = 'New %s created' % get_display_name(instance, classname) elif signal_type == SIGNAL_OBJECT_UPDATED: