def connect_signals(): from django.contrib.comments.signals import comment_was_posted from ella.core.signals import content_published, content_unpublished from django.db.models.signals import post_save content_published.connect(publishable_published) content_unpublished.connect(publishable_unpublished) comment_was_posted.connect(comment_posted, sender=comments.get_model()) post_save.connect(comment_post_save, sender=comments.get_model())
def moderate_comment(sender, comment, request, **kwargs): ak = akismet.Akismet( key = settings.AKISMET_API_KEY, blog_url = 'http://%s/' % Site.objects.get_current().domain ) data = { 'user_ip': request.META.get('REMOTE_ADDR', ''), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERRER', ''), 'comment_type': 'comment', } if ak.comment_check(smart_str(comment.comment), data=data, build_data=True): comment.is_public = False comment.save() if comment.is_public: email_body = "%s" mail_managers ("New comment posted", email_body % (comment.get_as_text())) comment_was_posted.connect(moderate_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)
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', )
if post.following.all(): for user in post.following.all(): if user != comment.user and user != post.get_owner() \ and comment.user not in user.get_blocked(): Notification(user=user, type='FC', other_user=comment.user, content_object=comment.content_object, related_object = comment).save() except: import logging logger = logging.getLogger(__name__) logger.warning('Error in notifications') #adding this post to following list comment.user.follows.add(comment.content_object.get_post()) comment_was_posted.connect(create_comment_notifiaction) def create_comment_image_notification(sender, instance, created, **kwargs): if created: if instance.owner != instance.image.get_owner() and instance.image.get_owner() in instance.image.following.all(): data = { 'user': instance.image.get_owner(), 'type': 'CI', 'other_user': instance.owner, 'content_object': instance.image, 'related_object': instance, } Notification.objects.create(**data) #create notifiactions for all followers of this post for user in instance.image.following.all():
def delete(request): """ Wrapper to make sure the user deleting a comment is the user who originally posted that comment. Also gets around moderation permissions by calling perform_delete() directly. """ comment = get_object_or_404(comments.get_model(), pk=request.POST.get('comment_id'), site__pk=settings.SITE_ID) if comment.user == request.user: django_comments_moderation.perform_delete(request, comment) messages.success(request, 'Your comment has been deleted') # should add some error handling here if 'next' is not in request.POST return redirect(request.POST.get('next')) else: raise Http404 def after_comment_has_been_posted(sender, comment, request, **kwargs): """ Function to run when the comments app fires the comment_was_posted signal. Can be configured to run some function called "after_comment_has_been_posted" defined by the user and in a module specified by the SIMPLE_COMMENTS_SIGNAL_MODULE setting """ if hasattr(settings, 'SIMPLE_COMMENTS_SIGNAL_MODULE'): signal_module = importlib.import_module(settings.SIMPLE_COMMENTS_SIGNAL_MODULE) signal_module.after_comment_has_been_posted(sender, comment, request, **kwargs) else: messages.success(request, 'Your comment has been posted!') comment_was_posted.connect(after_comment_has_been_posted)
from django.conf.urls.defaults import * from q.accounts.views import view_user, view_user_list, edit_profile urlpatterns = patterns('', url(r'^$', view_user_list, name="view_user_list"), url(r'(?P<username>[\w\d\-]+)/edit/$', edit_profile, name="edit_profile"), url(r'(?P<username>[\w\d\-]+)/$', view_user, name="view_user"), ) #handling comments from q.ebooks.listeners import activity_stream_comment from django.contrib.comments.models import Comment from django.contrib.comments.signals import comment_was_posted comment_was_posted.connect(activity_stream_comment)
# Registers the function with the django-registration user_activated signal user_activated.connect(login_on_activation) SYSTEM_USER_NAME = "YouAreHero" def get_system_user(): """Return an unique system-user. Creates one if not existing.""" user, created = User.objects.get_or_create(username=SYSTEM_USER_NAME) return user def get_dummy_user(): return UserProfile(user=User(username="******")) def experience_for_comment(sender, comment, request, **kwargs): if comment.user_id: profile = comment.user.profile profile.experience += COMMENT_EXPERIENCE profile.save() comment_was_posted.connect(experience_for_comment) def create_user_profile(instance, raw, created, using, **kwargs): if created: profile, created = UserProfile.objects.using(using).get_or_create(user=instance) post_save.connect(create_user_profile, sender=User)
if user != comment.user and user != post.get_owner() \ and comment.user not in user.get_blocked(): Notification(user=user, type='FC', other_user=comment.user, content_object=comment.content_object, related_object=comment).save() except: import logging logger = logging.getLogger(__name__) logger.warning('Error in notifications') #adding this post to following list comment.user.follows.add(comment.content_object.get_post()) comment_was_posted.connect(create_comment_notifiaction) def create_comment_image_notification(sender, instance, created, **kwargs): if created: if instance.owner != instance.image.get_owner( ) and instance.image.get_owner() in instance.image.following.all(): data = { 'user': instance.image.get_owner(), 'type': 'CI', 'other_user': instance.owner, 'content_object': instance.image, 'related_object': instance, } Notification.objects.create(**data) #create notifiactions for all followers of this post
class FollowUpMessage(models.Model): site = models.OneToOneField(Site) message = models.TextField() def __unicode__(self): return "%s: %s..." % (self.site.name, self.message[:15]) def send_followup_email(sender, **kwargs): instance = kwargs["comment"] follow_up_users = FollowUpComment.objects.filter(need_follow_up=True).values("user_email") site = Site.objects.get(id=settings.SITE_ID) subject = "[%s] Follow up to comment posted " "for %s at %s" % (site.name, instance.content_object, site.domain) followup_message = FollowUpMessage.objects.get(site__id=settings.SITE_ID).message message = """%s\n\n%s by %s at %s""" % ( followup_message, instance.comment, instance.user_name, instance.submit_date.strftime(settings.DATETIME_FORMAT), ) data_list = [] for user in follow_up_users: data_list.append([subject, message, None, [user["user_email"]]]) send_mass_mail(data_list) comment_was_posted.connect(send_followup_email)
comment = kwargs['comment'] if comment.parent: message = """ Dear %(recipient)s, Someone has replied to your comment on HTR. You may view and reply to this comment by logging in and viewing your post at: http://htr.mjs-svc.com%(url)s They said: %(body)s Please do not reply to this email. ~The HTR team """ % { 'recipient': comment.parent.user.username, 'url': comment.content_object.get_absolute_url(), 'body': comment.comment } send_mail("Reply to your comment: %s" % comment.content_object.title, message, '*****@*****.**', [comment.parent.user.email], fail_silently=False) comment_was_posted.connect(mail_author_on_comment) comment_was_posted.connect(mail_comment_parent_author_on_comment)
@login_required def post(request, next=None, using=None): """ This wrapper view only serves to require login for posting comments """ return django_comments.post_comment(request, next, using) @login_required @require_POST def delete(request): """ Wrapper to make sure the user deleting a comment is the user who originally posted that comment. Also gets around moderation permissions by calling perform_delete() directly. """ comment = get_object_or_404(comments.get_model(), pk=request.POST.get('comment_id'), site__pk=settings.SITE_ID) if comment.user == request.user: django_comments_moderation.perform_delete(request, comment) messages.success(request, 'Your comment has been deleted') # should add some error handling here if 'next' is not in request.POST return redirect(request.POST.get('next')) else: raise Http404 def comment_posted_message(sender, comment, request, **kwargs): messages.success(request, 'Your comment has been posted!') comment_was_posted.connect(comment_posted_message)
import lfc.utils from lfc.models import BaseContent 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)
Just thought you'd like to know! The Snipt team at Lion Burger. """ % (comment.name, snipt.description, snipt.get_absolute_url(), comment.id) html_content = """ <a href="http://snipt.net/%s">%s</a> has posted a comment on your snipt "<a href="http://snipt.net%s#comment-%s">%s</a>".<br /> <br /> Just thought you'd like to know!<br /> <br /> The <a href="http://snipt.net">Snipt</a> team at <a href="http://lionburger.com">Lion Burger</a>. """ % (comment.name, comment.name, snipt.get_absolute_url(), comment.id, snipt.description) msg = EmailMultiAlternatives("""A new comment on "%s".""" % snipt.description, text_content, 'Snipt <*****@*****.**>', [snipt.user.email]) msg.attach_alternative(html_content, "text/html") msg.send() comment_was_posted.connect(email_owner_on_comment) def snipt_page(request, user, snipt_id): try: snipt = Snippet.objects.get(slug=snipt_id) if 'c' in request.GET: return HttpResponseRedirect(snipt.get_absolute_url() + '#comment-' + request.GET['c']) except: return HttpResponseRedirect('/' + user + '/tag/' + snipt_id) context_user = User.objects.get(id=snipt.user.id) if request.user.id == context_user.id: mine = True else: mine = False
# 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 != user: notification.send([comment.parent.user], "comment_reply_received", infodict) else: notice_type_suffix = "posted" # Notifications of stuff I'm doing notification.send([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(request.user) if x['friend'] != comment.parent.user), "comment_friend_%s" % (notice_type_suffix, ), infodict ) if relationships: followers = request.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)
a = models.FloatField() b = models.FloatField() k = models.FloatField() class StockList(models.Model): stock_code = models.IntegerField(primary_key=True) stock_name = models.CharField(max_length=50) gradient = models.FloatField() trend = models.ForeignKey(StockTrend) def __unicode__(self): return self.stock_name class StockData(models.Model): stock_ref = models.ForeignKey(StockList) trade_date = models.DateField() open_price = models.FloatField() high_price = models.FloatField() low_price = models.FloatField() close_price = models.FloatField() volume = models.FloatField() quantity = models.FloatField() post_save.connect(Stream.add_post, sender=Post) post_save.connect(Likes.user_like_post, sender=Likes) post_save.connect(Post.change_tag_slug, sender=Tag) comment_was_posted.connect(user_comment_post, sender=Comment)
sender = models.ForeignKey(User, related_name="sender") user = models.ForeignKey(User, related_name="userid") text = models.CharField(max_length=500) seen = models.BooleanField(default=False) type = models.IntegerField(default=1, choices=TYPES) # 1=Post_like, 2=Post_comment def user_comment_post(sender, **kwargs): if 'pin.post' in kwargs['request'].POST['content_type']: comment = kwargs['comment'] post_id = kwargs['request'].POST['object_pk'] post = Post.objects.get(pk=post_id) if comment.user != post.user: #post = comment.post sender = comment.user notify = Notify() notify.post = post notify.sender = sender notify.user = post.user notify.text = 'comment this' notify.type = 2 notify.save() post_save.connect(Stream.add_post, sender=Post) post_save.connect(Likes.user_like_post, sender=Likes) post_save.connect(Post.change_tag_slug, sender=Tag) comment_was_posted.connect(user_comment_post, sender=Comment)
request_ip = models.CharField(max_length=20) request_type = models.CharField(max_length=10) request_timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) priority = models.PositiveSmallIntegerField(default=0) def __unicode__(self): return self.requested_url class DbActionsLog(models.Model): DELETED = "del" ALTERED = "alt" CREATED = "cre" ACTION_CHOICES = ((DELETED, "Delete"), (ALTERED, "Alter"), (CREATED, "Create")) model_name = models.CharField(max_length=30, verbose_name="Model name") action = models.CharField(max_length=3, verbose_name="Commited action", choices=ACTION_CHOICES) target_instance = models.CharField(max_length=255, blank=True, null=True, verbose_name="Target instance") timestamp = models.DateTimeField(auto_now_add=True, verbose_name="Timestamp") class Meta: verbose_name = "Database activity record" verbose_name_plural = "Database activity records" def __unicode__(self): return "%s %s %s %s" % (self.model_name, self.target_instance, self.action, self.timestamp) comment_was_posted.connect(moderate_comment) post_save.connect(models_change_log, dispatch_uid="create_or_update_object") post_delete.connect(models_change_log, dispatch_uid="delete_object")
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)
# signals def comment_handler(sender, comment, request, *args, **kwargs): discussion_thread_type = ContentType.objects.get(app_label='discuss', model='discussionthread') if comment.content_type == discussion_thread_type: # comment on a new or existing discuss thread thread = DiscussionThread.objects.get(pk=comment.object_pk) thread.last_comment_id = comment.id thread.save() else: # comment on other site content post/artwork/etc... try: thread = DiscussionThread.objects.get( content_type=comment.content_type, object_pk=comment.object_pk) except DiscussionThread.DoesNotExist: thread = DiscussionThread(content_type=comment.content_type, object_pk=comment.object_pk) thread.last_comment_id = comment.id thread.save() comment.title = thread.content_object.title comment.save() if not moderator.process(comment, request): send_to_discuss_mailing_list(comment, request) update_discuss_activity_stream(comment, request) comment_was_posted.connect(comment_handler, dispatch_uid='discuss.comment_handler')
'position', 'title', ) def __unicode__(self): return self.title def save(self, *args, **kwargs): self.slug = uuslug(self.title, instance=self) super(BlogCategory, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('post-list', args=[self.slug]) """ def add_comment_count(sender, comment, **kwargs): if comment.content_type.model == u'blogpost': post = BlogPost.objects.get(pk=comment.object_pk) post.add_comment_count() comment_was_posted.connect(add_comment_count) """ class Photo(models.Model): """ A photo that might attach to a blog post gallery. Which will be in slide show. """ ORIENTATIONS = (
img = models.ImageField(upload_to=upload_path, help_text="Maximum allowed size: " + str(settings.MAX_IMAGE_SIZE / 1024) + " kilobytes.") desc = models.CharField(max_length=200) issue = models.ForeignKey(Issue, related_name='images') def size_in_kb(self): return self.img.size / 1024 def __unicode__(self): return self.desc def comment_callback(sender, **kwargs): """ Handler for a signal when a comment is saved. Essentially, it finds out which Issue the comment is attached to, and updates its updated_date field. """ comment = kwargs['comment'] if comment.content_type.model_class() == Issue: issue = Issue.objects.get(id=comment.object_pk) issue.updated_date = datetime.datetime.now() issue.save() comment_was_posted.connect(comment_callback)
elif self.content_format == u'reST': self.summary_html = publish_parts( source=smart_str(self.summary), writer_name="html", settings_overrides=BLOG_DOCUTILS_SETTINGS)['fragment'] self.body_html = publish_parts( source=smart_str(self.body), writer_name="html", settings_overrides=BLOG_DOCUTILS_SETTINGS)['fragment'] super(Entry, self).save(*args, **kwargs) def moderate_comment(sender, comment, request, **kwargs): ak = akismet.Akismet(key=settings.AKISMET_API_KEY, blog_url='http://%s/' % Site.objects.get_current().domain) data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERRER', ''), 'comment_type': 'comment', 'comment_author': smart_str(comment.user_name), } if ak.comment_check(smart_str(comment.comment), data=data, build_data=True): comment.is_public = False comment.save() comment_was_posted.connect(moderate_comment)
from django.contrib.comments.signals import comment_was_posted from voting.models import Vote def auto_upvote_self_posts(sender, **kwargs): if "request" in kwargs and "comment" in kwargs: request = kwargs["request"] comment = kwargs["comment"] if request.user.is_authenticated(): Vote.objects.record_vote(comment, request.user, 1) comment_was_posted.connect(auto_upvote_self_posts)
return super(TicketAppelManager, self).get_query_set().\ select_related('user') class TicketAppel(models.Model): """ Liste de date où le client a rappelé """ class Meta: ordering = ["date"] objects = TicketAppelManager() date = models.DateTimeField(auto_now_add=True) ticket = models.ForeignKey(Ticket) user = models.ForeignKey(User) def save(self, *args, **kwargs): ticket = Ticket.minimal.get(pk=self.ticket.pk) # peut être mieux de recalculer à chaque fois .... ticket.nb_appels = models.F('nb_appels') + 1 ticket.save() return super(TicketAppel, self).save(*args, **kwargs) #moderator.register(Ticket, TicketCommentModerator) # Update last_modification time comment_was_posted.connect(Ticket.handle_comment_posted_signal) # Google calendar sync models.signals.pre_save.connect(Ticket.handle_ticket_presave_signal, sender=Ticket)
post_save.connect(add_post_to_followings, sender=PagePost) post_save.connect(add_post_to_followings, sender=FeedbackPost) def add_user_to_following_discussion(sender, instance, created, **kwargs): if created: if instance.user not in instance.topic.following.all(): instance.topic.following.add(instance.user) post_save.connect(add_user_to_following_discussion, sender=DiscussPost) def add_user_to_following_discussion_by_comment(sender, comment, request, **kwargs): if comment.content_object: post = comment.content_object.get_inherited() if isinstance(post, DiscussPost): if comment.user not in post.topic.following.all(): post.topic.following.add(comment.user) comment_was_posted.connect(add_user_to_following_discussion_by_comment) def update_news_feeds(sender, instance, created, **kwargs): if created: UpdateNewsFeeds.delay(instance.get_inherited()) post_save.connect(update_news_feeds, sender=FriendPost) post_save.connect(update_news_feeds, sender=ContentPost) post_save.connect(update_news_feeds, sender=SharePost) post_save.connect(update_news_feeds, sender=PagePost) post_save.connect(update_news_feeds, sender=PageSharePost) def delete_news_feeds(sender, instance, **kwargs): """Deletes original post""" try: post = instance.post post.delete()
else: history_group = history_group.none() for h in history_group: h.plmobject.plmobject_url = h.plmobject.groupinfo.plmobject_url if (list_display["display_document"] or list_display["display_part"] ) and list_display["display_group"]: history = sorted(chain(history_group, history_plmobject), key=lambda instance: instance.date, reverse=True) elif list_display["display_group"]: history = history_group elif list_display["display_document"] or list_display["display_part"]: history = history_plmobject return history def _save_comment_history(sender, comment, request, **kwargs): """ Save an history line when a comment is posted. """ from openPLM.plmapp.controllers import get_controller obj = comment.content_object ctrl_cls = get_controller(obj.__class__.__name__) ctrl = ctrl_cls(comment.content_object, request.user, no_index=True) ctrl._save_histo("New comment", comment.comment) comment_was_posted.connect(_save_comment_history)
from django.db.models import signals from django.contrib.auth.models import User from subscription.models import Subscription APPS = settings.INSTALLED_APPS if 'django.contrib.comments' in APPS: from django.contrib.comments.models import Comment from django.contrib.comments.signals import comment_was_posted def auto_subscribe_user_to_his_comments(sender, **kwargs): comment = kwargs.pop('comment') user = comment.user Subscription.objects.subscribe(user, comment) comment_was_posted.connect(auto_subscribe_user_to_his_comments) def emit_new_comment(comment): Subscription.objects.emit( u'%(actor)s commented on %(target)s', subscribers_of=comment.content_object, dont_send_to=[comment.user], context={ 'comment': comment, }, actor=comment.user, queue='chat', ) if getattr(settings, 'USE_COMMENTS_AS_WALL', False): from django.contrib.comments.signals import comment_was_posted
self.submit_date = datetime.datetime.now() super(CommentSimple, self).save(force_insert, force_update) def callback_comment_posted(**kwargs): sender = kwargs['sender'] comment = kwargs['comment'] request = kwargs['request'] constituency = comment.content_object users = constituency.customuser_set.filter(is_active=True, unsubscribed=False) for user in users: if user != comment.user: try: notify_obj = NotifyComment.objects.get(user=user, constituency=constituency) except NotifyComment.DoesNotExist: notify_obj = None if notify_obj: if notify_obj.notify_type == NotifyComment.Types.every: notify_obj.send_email(comment, False) else: # Send the email and notifications will be deactivated in the future notify_obj = NotifyComment.objects.create(user=user, constituency=constituency, notify_type=NotifyComment.Types.none) notify_obj.send_email(comment, True) comment_was_posted.connect(callback_comment_posted)
try: from django.contrib.comments.models import Comment from django.contrib.comments.signals import comment_will_be_posted, comment_was_posted except ImportError: from django_comments.models import Comment from django_comments.signals import comment_will_be_posted, comment_was_posted from listeners import * 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)
# -*- coding: utf-8 -*- from django.contrib.comments.models import Comment from django.contrib.comments.signals import comment_was_posted from django.db.models import BooleanField from django.utils.translation import ugettext_lazy as _ from signals import lift_method class CustomComment(Comment): lift_method = BooleanField(_("Lift method?"), default=True, blank=True, db_index=True) class Meta: verbose_name = _("comment") verbose_name_plural = _("comments") comment_was_posted.connect(lift_method)
# delete the item from cache absolute_url = content_object.get_absolute_url() language_code = content_object.language.code delete_cache_item(absolute_url, language_code, site.id) # FIXME: We must only update the cache for the current SITE not for all sites. try: cache.smooth_update() # Save "last change" timestamp in django-tools SmoothCacheBackend except AttributeError: # No SmoothCacheBackend used -> clean the complete cache cache.clear() comment_will_be_posted.connect(comment_will_be_posted_handler) comment_was_posted.connect(comment_was_posted_handler) @ensure_csrf_cookie @check_request(APP_LABEL, "_get_form() error", must_post=False, must_ajax=True) @render_to("pylucid_comments/comment_form.html") def _get_form(request): """ Send the comment form to via AJAX request """ try: ctype = request.GET["content_type"].split(".", 1) model = models.get_model(*ctype) except Exception, err: return bad_request(APP_LABEL, "error", "Wrong content type: %s" % err) try: object_pk = request.GET["object_pk"]
def join_astrocourse(sender, instance, **kwargs): """ When a user joins astrocourse, and their profile is created """ if kwargs['created']: action.send(instance.user, verb="joined astrocourse!") def post_resource(sender, instance, **kwargs): """ When a user starts a resource in a course """ if kwargs['created']: action.send(instance.author, verb="posted a resource:", action_object=instance, target=instance.course) def post_question(sender, instance, **kwargs): """ When a user posts a question in a course """ if kwargs['created']: action.send(instance.author, verb="posted a question:", action_object=instance, target=instance.course) def earned_award(sender, instance, **kwargs): """ When a user earns an award """ if instance.earned: action.send(instance.user.user, verb="earned", action_object=instance.award, target=instance) comment_was_posted.connect(comment_on, sender=Comment, dispatch_uid="actstream.comment_on") models.signals.post_save.connect(create_course, sender=Course, dispatch_uid="actstream.create_course") models.signals.post_save.connect(join_astrocourse, sender=UserProfile, dispatch_uid="actstream.join_astrocourse") models.signals.post_save.connect(post_resource, sender=Resource, dispatch_uid="actstream.post_resource") models.signals.post_save.connect(post_question, sender=Question, dispatch_uid="actstream.post_question") models.signals.post_save.connect(earned_award, sender=Awarded, dispatch_uid="actstream.earned_award") models.signals.post_save.connect(guinea_pig, sender=UserProfile, dispatch_uid="award.guinea_pig") models.signals.post_save.connect(builder, sender=Enrollment, dispatch_uid="award.builder") models.signals.post_save.connect(the_inquirer, sender=Question, dispatch_uid="award.the_inquirer")
class Meta: verbose_name_plural = 'News' ordering = ['-last_updated_date', '-created_date'] def send_comment_notif(sender, comment, request, **kwargs): """ fungsi untuk membuat notification ketika ada komentar yang dipostkan """ messages.info(request, _('Your comment "%s" sucessfully posted') % comment.comment) if request.user != comment.content_object.user: notification.send([comment.content_object.user], "news_comment", { 'user': request.user, 'news': comment.content_object }) from utils.rest import send_comments from django.template.loader import render_to_string send_comments({ 'content': render_to_string('comment_item.html', {'comment' : comment}) }) def comment_flagged(sender, comment, flag, created, request, **kwargs): """ fungsi untuk membuat pesan info jika komentar di flag """ if created: messages.info(request, _('Comment "%s" flagged') % comment) comment_was_posted.connect(send_comment_notif, dispatch_uid="new_news_comment") comment_was_flagged.connect(comment_flagged, dispatch_uid="comment_flagged")
htmly = get_template(os.path.join(settings.PROJECT_PATH, "templates/cmsplugin_blog/email_replied.html")) subject = _('Reply to your comment') text_content = plaintext.render(context_dict) html_content = htmly.render(context_dict) msg = EmailMultiAlternatives(subject, text_content, getattr(settings,'CMSPLUGIN_BLOG_EMAIL_FROM', 'noreply@%s' % Site.objects.get(pk=settings.SITE_ID).domain), [to]) msg.attach_alternative(html_content, "text/html") msg.send() except AttributeError: return if getattr(settings, 'CMSPLUGIN_BLOG_COMMENT_NOTIFICATIONS', False): comment_was_posted.connect(on_comment_was_posted_notification) def on_comment_was_posted_spamcheck(sender, comment, request, *args, **kwargs): """ Defines action for django.contrib.comments on_comment_was_posted signal. Provides anti-spam via the Akismet and TypePad Antispam services. Both services require the akismet package. Fails silently if the Akismet package is not available. """ try: from akismet import Akismet except: return # use TypePad's AntiSpam if the key is specified in settings.py if hasattr(settings, 'TYPEPAD_ANTISPAM_API_KEY'): ak = Akismet(
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(): template_arg = [
def attach_comment_listener(func=moderate_comment): comment_was_posted.connect(func, sender=Comment, dispatch_uid='djutils.spam.comments.listeners')
return render_to_response( 'subwayrating/view_comment.html', {'stop_comment': get_object_or_404(SubwayStop, slug=slug)}, context_instance=RequestContext(request)) def top_n_stops(request): reviews = SubwayStop.objects.all() return render_to_response('subwayrating/list.html', {'reviews': heapq.nlargest(5, reviews)}, context_instance=RequestContext(request)) def bottom_n_stops(request): reviews = SubwayStop.objects.all() return render_to_response('subwayrating/list.html', {'reviews': heapq.nsmallest(5, reviews)}, context_instance=RequestContext(request)) def comment_messages(sender, comment, request, **kwargs): if request.user.is_authenticated(): messages.add_message(request, messages.SUCCESS, _('Thank you for your comment!')) else: messages.add_message(request, messages.INFO, _('No comments without authentication')) comment_was_posted.connect(comment_messages, sender=CommentWithRating)
import django from django.db import models from django.contrib.comments.signals import comment_was_posted from actstream import action def comment_action(sender, comment=None, target=None, **kwargs): if comment.user: action.send(comment.user, verb=u'commented', action_object=comment, target=comment.content_object) comment_was_posted.connect(comment_action) class Player(models.Model): state = models.IntegerField(default=0) def __unicode__(self): return '#%d' % self.pk if django.VERSION[0] == 1 and django.VERSION[1] >= 5: from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin class MyUser(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=30, unique=True) USERNAME_FIELD = 'username' def get_full_name(self): return 'full'
from techblog import signal_listeners from registration.signals import user_activated from django.contrib.comments.signals import comment_was_posted user_activated.connect(signal_listeners.on_user_activate) comment_was_posted.connect(signal_listeners.on_article_comment)
from enuff.managers import EnuffManager Comment = comments.get_model() def update_thread(sender, request, **kwargs): instance = kwargs.get('comment') if instance.content_object.__class__ == Thread: x = instance.content_object x.latest_post = instance x.posts += 1 x.save() x.forum.posts += 1 x.forum.save() Thread.nonrel_objects.push_to_list("%s-latest-threads" % x.forum.slug, x, trim=25) comment_was_posted.connect(update_thread,sender=Comment) from forum.managers import ForumManager class Forum(models.Model): """ Very basic outline for a Forum, or group of threads. The threads and posts fielsd are updated by the save() methods of their respective models and are used for display purposes. All of the parent/child recursion code here is borrowed directly from the Satchmo project: http://www.satchmoproject.com/ """ allowed_users = models.ManyToManyField('auth.User',blank=True,related_name="allowed_forums",help_text="Ignore if non-restricted") title = models.CharField(_("Title"), max_length=100) slug = models.SlugField(_("Slug"))
data = { 'user_ip': request.META.get('REMOTE_ADDR', '127.0.0.1'), 'user_agent': request.META.get('HTTP_USER_AGENT', ''), 'referrer': request.META.get('HTTP_REFERER', ''), 'comment_type': 'comment', 'comment_author': comment.user_name.encode('utf-8'), } # If it's spam... if ak.comment_check(comment.comment.encode('utf-8'), data=data, build_data=True): comment.flags.create( user=comment.content_object.author, flag='spam' ) comment.is_public = False comment.is_removed = True comment.save() # If it's not... else: # Send an email recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS] t = loader.get_template('comments/comment_notification_email.txt') c = Context({ 'comment': comment, 'content_object': comment.content_object }) subject = '[%s] New comment posted on "%s"' % (Site.objects.get_current().name, comment.content_object) message = t.render(c) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True) comment_was_posted.connect(on_comment_was_posted)
topic_type = ContentType.objects.get(app_label="topics", model="topic") comments = Comment.objects.filter(content_type=topic_type) return comments.count() def top_comments(num=10): from django.contrib.comments import models as comment_models comment_opts = comment_models.Comment._meta comment_table_name = comment_opts.db_table ctype = ContentType.objects.get(app_label="topics", model="topic") return Topic.objects.extra(select={ 'c_count': 'SELECT COUNT(*) FROM %s WHERE content_type_id = %s AND is_public = 1' % (comment_table_name, ctype.id) }, ).order_by('-c_count')[0:num] # 让comment 与 topic通信,当有新的评论产生后, # 则在topic中修改最后回复时间 def last_reply(sender, comment, **kwargs): if comment.is_public: t = Topic.objects.get(pk=comment.object_pk) t.last_reply = comment.submit_date t.comments_count = F('comments_count') + 1 t.save() comment_was_posted.connect(last_reply, sender=Comment)
# -----------------------------------------------------------------------------# from django.contrib import messages from django.utils.translation import ugettext as _ from django.contrib.comments import Comment from django.contrib.comments.signals import comment_was_posted # -----------------------------------------------------------------------------# """ Overide the comment system with custom behavior This doesn't work in the custom comments app. """ # -----------------------------------------------------------------------------# def comment_messages(sender, comment, request, **kwargs): messages.add_message(request, messages.INFO, _("Thank you for your comment!")) comment_was_posted.connect(comment_messages, sender=Comment)
if done_by != "": if User.objects.filter(username= done_by).exists(): history_group = history_group.filter(user__username = done_by) else: history_group = history_group.none() for h in history_group: h.plmobject.plmobject_url = h.plmobject.groupinfo.plmobject_url if (list_display["display_document"] or list_display["display_part"]) and list_display["display_group"]: history = sorted(chain(history_group, history_plmobject), key=lambda instance: instance.date, reverse=True) elif list_display["display_group"]: history = history_group elif list_display["display_document"] or list_display["display_part"]: history = history_plmobject return history def _save_comment_history(sender, comment, request, **kwargs): """ Save an history line when a comment is posted. """ from openPLM.plmapp.controllers import get_controller obj = comment.content_object ctrl_cls = get_controller(obj.__class__.__name__) ctrl = ctrl_cls(comment.content_object, request.user, no_index=True) ctrl._save_histo("New comment", comment.comment) comment_was_posted.connect(_save_comment_history)
from django.db import models from django.template.defaultfilters import slugify from south.modelsinspector import add_introspection_rules from addac.tagging.models import Tag from addac.tagging_autocomplete.models import TagAutocompleteField from thumbs import ImageWithThumbsField from addac.utils import get_image_path add_introspection_rules( [], ["^addac\.tagging_autocomplete\.models\.TagAutocompleteField"]) from django.contrib.comments.moderation import CommentModerator, moderator, AlreadyModerated from django.contrib.comments.models import Comment from django.contrib.comments.signals import comment_was_posted from addac.noticias.signals import comment_notifier comment_was_posted.connect(comment_notifier, sender=Comment) class CategoriaNoticia(models.Model): '''Modelo que representa la categorias de las noticias''' nombre = models.CharField('Título', max_length=40, unique=True, blank=True, null=True) slug = models.SlugField(max_length=40, unique=True, help_text='unico Valor', editable=False) def __unicode__(self):
target=comment) Follow.objects.get_or_create(comment.user, comment) actions.follow(comment.user, comment, send_action=False, actor_only=False) elif isinstance(comment.content_object, ThreadedComment): action.send(comment.user, verb=settings.REVIEW_COMMENT_VERB, action_object=comment, target=comment.content_object, batch_time_minutes=30, is_batchable=True) elif isinstance(comment.content_object, Album): action.send(comment.user, verb=settings.ALBUM_COMMENT_VERB, action_object=comment, target=comment.content_object, batch_time_minutes=30, is_batchable=True) elif isinstance(comment.content_object, Image): action.send(comment.user, verb=settings.IMAGE_COMMENT_VERB, action_object=comment, target=comment.content_object, batch_time_minutes=30, is_batchable=True) elif isinstance(comment.content_object, BroadcastWish): action.send(comment.user, verb=settings.WISH_COMMENT_VERB, action_object=comment, target=comment.content_object, batch_time_minutes=30, is_batchable=True) Follow.objects.get_or_create(comment.user, comment.content_object) actions.follow(comment.user, comment.content_object, send_action=False, actor_only=False) elif isinstance(comment.content_object, BroadcastDeal): action.send(comment.user, verb=settings.DEAL_COMMENT_VERB, action_object=comment, target=comment.content_object, batch_time_minutes=30, is_batchable=True) Follow.objects.get_or_create(comment.user, comment.content_object) actions.follow(comment.user, comment.content_object, send_action=False, actor_only=False) elif isinstance(comment.content_object, GenericWish): action.send(comment.user, verb=settings.POST_COMMENT_VERB, action_object=comment, target=comment.content_object, batch_time_minutes=30, is_batchable=True) Follow.objects.get_or_create(comment.user, comment.content_object) actions.follow(comment.user, comment.content_object, send_action=False, actor_only=False) comment_was_posted.connect(comment_action)
from django.core.mail import mail_managers from django.dispatch import dispatcher from django.contrib.auth.models import User from django.db.models.signals import post_save from django.contrib.comments.signals import comment_was_posted from kamu.comments.models import KamuComment import settings def comment_notification(sender, comment, request, **kwargs): subject = 'New comment on %s' % str(comment.content_object) msg = u'Comment from: %s (%s)\n\n' % (comment.user_name, request.META['REMOTE_ADDR']) msg += u'Comment text:\n\n%s\n' % comment.comment mail_managers(subject, msg, fail_silently=True) comment_was_posted.connect(comment_notification, sender=KamuComment) def user_notification(sender, instance, **kwargs): if (not 'created' in kwargs) or (not kwargs['created']): return user = instance subject = u"New user '%s' created" % (user.username) msg = u"Email '%s'\n" % (user.email) mail_managers(subject, msg, fail_silently=True) post_save.connect(user_notification, sender=User, dispatch_uid="user_email_notification")
m = Member.objects.get(pk=mk_id) if Action.objects.filter(actor_object_id=m.id, actor_content_type=member_ct, verb='attended', target_object_id=meeting.id, target_content_type=cm_ct).count()==0: action.send(m, verb='attended', target=meeting, description='committee meeting', timestamp=meeting.date) m2m_changed.connect(record_committee_presence, sender=CommitteeMeeting.mks_attended.through) @disable_for_loaddata def handle_annotation_save(sender, created, instance, **kwargs): if created: action.send(instance.content_object.meeting, verb='annotation-added', target=instance, description=unicode(instance.flag_value)) action.send(instance.user, verb='annotated', target=instance, description=unicode(instance.flag_value)) follow(instance.user, instance.content_object.meeting) post_save.connect(handle_annotation_save, sender=Annotation) @disable_for_loaddata def handle_comment_save(sender, comment, request, **kwargs): action.send(comment.content_object, verb='comment-added', target=comment, description=comment.comment) follow(request.user, comment.content_object) comment_was_posted.connect(handle_comment_save) def delete_related_activities(sender, instance, **kwargs): Action.objects.filter(target_object_id=instance.id, verb__in=('annotated', 'comment-added')).delete() pre_delete.connect(delete_related_activities, sender=Annotation) pre_delete.connect(delete_related_activities, sender=Comment)
def on_comment_post(cls, comment, request, **kwargs): if comment.content_object.__class__ == cls: view_time, created = BlogPostView.objects.get_or_create(user=request.user, post=comment.content_object) view_time.timestamp = datetime.now() view_time.save() def last_view(self, user): views = self.last_view_objs.filter(user=user).order_by('-timestamp') if len(views) > 0: return views[0].timestamp else: return datetime.now() post_save.connect(BlogPost.on_comment_create, sender=get_model()) pre_delete.connect(BlogPost.on_comment_delete, sender=get_model()) comment_was_posted.connect(BlogPost.on_comment_post, sender=get_model()) class BlogSubscription(models.Model): user = models.ForeignKey(User) blog = models.ForeignKey(Blog) created = models.DateTimeField(auto_now_add=True) def __unicode__(self): return "{0}: {1}".format(self.blog, self.user.username) class Meta: verbose_name = _(u'подписка') verbose_name_plural = _(u'подписки')
else: username = "******" for user in ticket.authorized_users.all(): recipients.append(user.email) if ticket.assigned_to is not None: recipients.append(ticket.assigned_to.email) while kwargs['request'].user.email in recipients: recipients.remove(kwargs['request'].user.email) message = EmailMessage(username + " has commented on your ticket", \ "<html><body>Ticket: <a href='" + \ kwargs['request'].build_absolute_uri( reverse('tickets.views.show_ticket', kwargs={'ticket_id': ticket.id})) + \ "'>" + ticket.title + "</a><br>" + \ "Message: " + kwargs['comment'].comment + "<br>" +\ "</body></html>", \ settings.SERVER_EMAIL, recipients) message.content_subtype = "html" message.send() def save_last_modified(sender, **kwargs): if sender == LogEntry and kwargs['instance'].get_edited_object( ).__class__ == Ticket: ticket = kwargs['instance'].get_edited_object() user = kwargs['instance'].user.get_full_name() ticket.last_modified_by = user ticket.save() comment_was_posted.connect(notify_users) post_save.connect(save_last_modified)
except: shipping_address = other_addresses[0] shipping_address.is_billing = True shipping_address.save() if len(other_addresses) == 0: raise LastAddress self.deleted = True self.save(clean=True) def notify_about_comment(sender, **kwargs): comment = kwargs['comment'] subject = _("Nowy komentarz do produktu %s" % comment.content_object.name) subject = ''.join(subject.splitlines()) message = render_to_string('email/new_comment.html', { 'comment': comment, }) from django.core.mail import send_mail send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, settings.SHOP_STAFF_EMAILS) from django.contrib.comments.signals import comment_was_posted # cholera wie czemu wysyla sygnaly po dwa razy, ponizej chamowate # obejscie, za pomoca argumentu dispatch_uid, wiecej info tu: # http://www.mail-archive.com/[email protected]/msg71068.html comment_was_posted.connect(notify_about_comment, Comment, dispatch_uid='comment.post_comment')