예제 #1
0
def on_comment_created(sender, **kwargs):
    """
    Handle Creation of attachments
    @TODO: This needs to be abstracted!
    @CODESMELL
    """
    if not isinstance(sender, LogEntry):
        send = False
        is_new = kwargs.get('created', False)
        comment = kwargs.get('instance')
        extra = {}

        if comment and is_new:
            content_object_type = type(comment.content_object)
            logger.debug('New Comment on object type: {content_object_type}'.format(content_object_type=content_object_type))

            # If its a comment on a ToDo Object
            if content_object_type == ToDo:
                send = True
                target = todo = comment.content_object
                event = 'todo.comment.created'
                verb = u'{name} commented on checklist item {todo} for {project}'.format(name=comment.user.get_full_name(), project=todo.project, todo=todo.name).encode('utf-8')

                # update the ToDo Status as its been interacted with
                todostatus_service = ToDoStatusService(todo_item=todo)
                todostatus_service.process()

            elif content_object_type == Project:
                send = True
                target = project = comment.content_object
                event = 'project.comment.created'
                verb = u'{name} commented on the {project} project'.format(name=comment.user.get_full_name(), project=project).encode('utf-8')
                extra.update({
                    'url': comment.absolute_deeplink_url()  # append url to the comment deeplink
                })

            elif content_object_type == ProjectLawyer:
                send = True
                target = comment_target = comment.content_object
                event = 'project.lawyer_engage.comment.created'
                verb = u'{name} commented on the Lawyer Engagement conversation for {project}'.format(name=comment.user.get_full_name(), project=comment_target.project).encode('utf-8')

                # notify the lawyer (used for discussion counts)
                if comment.user.profile.is_customer:
                    recipient = comment.content_object.lawyer.user
                else:
                    recipient = comment.content_object.project.customer.user
                # send notification
                notify.send(comment.user, recipient=recipient, verb=u'added to discussion', action_object=comment_target.project,
                    description=comment.comment, target=comment_target.project, project_action='added_discussion_item', project_pk=comment_target.project.pk, creating_user_pk=comment.user.pk)

        if send is True:
            logger.debug(u'send action: {event} {verb} content: {content}'.format(event=event, verb=verb, content=comment.comment).encode('utf-8'))
            action.send(comment.user,
                        verb=verb,
                        action_object=comment,
                        target=target,
                        content=comment.comment,
                        event=event,
                        **extra)
예제 #2
0
 def save(self, sender, parent_msg=None):
     recipients = self.cleaned_data['recipient']
     subject = self.cleaned_data['subject']
     body = self.cleaned_data['body']
     message_list = []
     for r in recipients:
         msg = Message(
             sender = sender,
             recipient = r,
             subject = subject,
             body = body,
         )
         if parent_msg is not None:
             msg.parent_msg = parent_msg
             parent_msg.replied_at = datetime.datetime.now()
             parent_msg.save()
         msg.save()
         message_list.append(msg)
         notify.send(sender, url=msg.get_absolute_url(),recipient=r, verb=u'给你发送了一条新私信',)
         if notification:
             if parent_msg is not None:
                 notification.send([sender], "messages_replied", {'message': msg,})
                 notification.send([r], "messages_reply_received", {'message': msg,})
             else:
                 notification.send([sender], "messages_sent", {'message': msg,})
                 notification.send([r], "messages_received", {'message': msg,})
     return message_list
예제 #3
0
def vote_answer(request, ans_id):
	"""
	handles the upvoting event, updates the Vote model, and sends notification to User
	"""
	if request.method == 'POST':
		vote = (request.POST.get('vote') == "true")
		answer = Answer.objects.get(pk=ans_id)
		Vote.objects.record_vote(answer, request.user, vote)
		if vote:
			notify.send(request.user, recipient=answer.answered_by, verb=u'upvoted', action_object=answer, target=answer)
		else:
			notification_old = Notification.objects.filter(actor_object_id=request.user.id, verb=u'upvoted', action_object_object_id=ans_id)
			if notification_old:
				notification_old[0].delete()
		response_data = {}
		response_data['updated_vote'] = Vote.objects.get_votes(answer)
		response_data['pk'] = answer.pk
		return HttpResponse(
			json.dumps(response_data),
			content_type="application/json"
		)
	return HttpResponse(
			json.dumps({"nothing to see": "this isn't happening"}),
			content_type="application/json"
		)
예제 #4
0
    def setUp(self):
        self.message_count = 10
        self.other_user = User.objects.create(username="******",
                                              password="******",
                                              email="*****@*****.**")

        self.from_user = User.objects.create(username="******",
                                             password="******",
                                             email="*****@*****.**")
        self.to_user = User.objects.create(username="******",
                                           password="******",
                                           email="*****@*****.**")
        self.to_group = Group.objects.create(name="to2_g")

        self.to_group.user_set.add(self.to_user)
        self.to_group.user_set.add(self.other_user)

        for i in range(self.message_count):
            notify.send(self.from_user,
                        recipient=self.to_user,
                        verb='commented',
                        action_object=self.from_user)
        # Send notification to group
        notify.send(self.from_user,
                    recipient=self.to_group,
                    verb='commented',
                    action_object=self.from_user)
        self.message_count += self.to_group.user_set.count()
예제 #5
0
def on_project_created(sender, **kwargs):
    """
    Handle new Project
    """
    is_new = kwargs.get('created')
    project = kwargs.get('instance')

    # ensure that we have a project object and that is has NO pk
    # as we dont want this event to happen on change of a project
    if is_new:
        from .services.email import SendNewProjectEmailsService
        from .services.project_checklist import ProjectCheckListService

        # perform the bulk create event
        # to bring project up to date with any modifications made
        checklist_service = ProjectCheckListService(is_new=is_new, project=project)
        checklist_service.bulk_create()

        user = project.customer.user
        comment = u'{user} created this Project'.format(user=user.get_full_name())
        logger.debug(comment)

        # send notification
        notify.send(user, recipient=user, verb=u'created', action_object=project,
                    description=comment, target=project, project_action='created_project', project_pk=project.pk, creating_user_pk=user.pk)

        send = SendNewProjectEmailsService(project=project, sender=user)
        send.process()
예제 #6
0
    def save(self, note=None):
        entry = ShiftLogEntry.objects.create(
            person=self.profile,
            entry_type=ShiftLogEntry.VERIFY,
            note=note,
            )

        instance = self.cleaned_data["pk"]
        workshifter = instance.workshifter or instance.liable
        pool_hours = workshifter.pool_hours.get(pool=instance.pool)

        # Check if the shift was previously verified or marked as blown
        _undo_verify_blown(instance, pool_hours)

        instance.verifier = self.profile
        instance.closed = True
        instance.logs.add(entry)
        instance.save()

        pool_hours.standing += instance.hours
        pool_hours.save()

        if self.profile != workshifter:
            notify.send(self.profile.user, verb="verified", action_object=instance,
                        recipient=workshifter.user)

        return instance
예제 #7
0
def nuevo_reporte_usuario(request):
	usuario_reportador = request.user
	usuario_reportado = Usuario.objects.get(id = int(request.POST['perfil_id']))
	tipo = request.POST['razon']
	descripcion = request.POST['descripcion']

	reporte_usuario = ReporteUsuario()
	reporte_usuario.usuario_reportador = usuario_reportador
	reporte_usuario.usuario_reportado = usuario_reportado
	reporte_usuario.tipo = tipo
	reporte_usuario.descripcion = descripcion

	reporte_usuario.save()
	num_reportes = ReporteUsuario.objects.filter(usuario_reportado = usuario_reportado).count()
	key_sesion = session_from_usuario(usuario_reportado.id)

	if (num_reportes >= MAX_REPORTES):
		r = redis.StrictRedis(host='localhost', port=6379, db=0)
		r.publish('usuario_reportado', '{"session_key": "' + str(key_sesion) + '" }')

		notify.send(
	            reporte_usuario,
	            description= reporte_usuario.usuario_reportado.username + ' ha sido reportado mas de '+str(MAX_REPORTES)+' veces ',
	            recipient=reporte_usuario.usuario_reportado,
	            target=reporte_usuario.usuario_reportador,
	            verb= 'usuario_reportado'
	        )

	return HttpResponseRedirect('/?mensaje=Reporte%20creado%20correctamente')
예제 #8
0
    def save(self, note=None):
        entry = ShiftLogEntry.objects.create(
            person=self.profile,
            entry_type=ShiftLogEntry.VERIFY,
            note=note,
        )

        instance = self.cleaned_data["pk"]
        workshifter = instance.workshifter or instance.liable
        pool_hours = workshifter.pool_hours.get(pool=instance.pool)

        # Check if the shift was previously verified or marked as blown
        _undo_verify_blown(instance, pool_hours)

        instance.verifier = self.profile
        instance.closed = True
        instance.logs.add(entry)
        instance.save()

        pool_hours.standing += instance.hours
        pool_hours.save()

        if self.profile != workshifter:
            notify.send(self.profile.user,
                        verb="verified",
                        action_object=instance,
                        recipient=workshifter.user)

        return instance
예제 #9
0
def nuevo_comentario(request):
	contenido = request.GET['comentario']
	id_post = request.GET['id_post']
	id_usuario = request.GET['id_usuario']

	usuario = Usuario.objects.get(id = id_usuario)
	nota = Nota.objects.get(id = id_post)

	comentario = Comentario()

	comentario.contenido = contenido
	comentario.usuario = usuario
	comentario.nota = nota

	comentario.save()

	key_sesion = session_from_usuario(nota.usuario.id)

	r = redis.StrictRedis(host='localhost', port=6379, db=2)
	mensaje = '{ "session_key": "' + str(key_sesion) + '", "usuario": "' + comentario.usuario.username + '", "contenido": "' + comentario.contenido + '", "nota_id": ' + str(comentario.nota.id) + ', "nota": "' + comentario.nota.titulo + '", "fecha": "' + naturaltime(comentario.fecha) + '" }'
	r.publish('comentario', mensaje)

	if (request.user != nota.usuario):
		notify.send(
	            comentario,
	            description= usuario.username + ' ha hecho un comentario nuevo en ' + comentario.nota.titulo,
	            recipient=comentario.nota.usuario,
	            target=nota,
	            verb= 'nuevo_comentario'
	        )

	comentario_json = {'comentario_id': comentario.id, 'contenido': comentario.contenido, 'usuario': usuario.username, 'imagen': str(usuario.foto)}

	return JsonResponse(comentario_json, safe=False)
예제 #10
0
def nuevo_reporte_post(request):
	usuario = request.user
	nota = Nota.objects.get(id = int(request.POST['publicacion_id']))
	tipo = request.POST['razon']
	descripcion = request.POST['descripcion']

	reporte_nota = ReporteNota()
	reporte_nota.usuario = usuario
	reporte_nota.nota = nota
	reporte_nota.tipo = tipo
	reporte_nota.descripcion = descripcion

	reporte_nota.save()
	num_reportes = ReporteNota.objects.filter(nota = nota).count()
	key_sesion = session_from_usuario(nota.usuario.id)

	if (num_reportes >= MAX_REPORTES):
		r = redis.StrictRedis(host='localhost', port=6379, db=0)
		r.publish('nota_reportada', '{"session_key": "' + str(key_sesion) + '", "nota_id": "' +str(nota.id)+ '", "nota": "'+ nota.titulo +'" }')

		notify.send(
	            reporte_nota,
	            description= str(nota) + ' ha sido reportada mas de '+str(MAX_REPORTES)+' veces ',
	            recipient=nota.usuario,
	            target=nota,
	            verb= 'nota_reportada'
	        )

	return HttpResponseRedirect('/?mensaje=Reporte%20creado%20correctamente')
예제 #11
0
    def emit(self, record):
        from django.contrib.auth.models import User
        from notifications import notify
        from notifications.models import Notification
        message = record.getMessage()
        if record.exc_text:
            message += "\n\n"
            message = message + record.exc_text

        notification_title_level = record.levelname.title()
        try:
            users = User.objects.filter(is_superuser=True).distinct()

            for user in users:
                notify.send(
                    user,
                    recipient=user,
                    level=record.levelname,
                    verb=f"{record.name}",
                    description=f"{message}",
                    public=False,
                )
        except OperationalError:
            pass # in migration
        except ProgrammingError:
            pass # in migration
예제 #12
0
def notify_achievement_unlocked(sender, instance, created, **kwargs):
    """
    Notifies a user that they have unlocked an achievement.

    @param sender: The model class
    @param instance: Instance of the model class being saved
    @param created: True if this is newly created.
    @param kwargs: Dictionary of key-value arguments.
    @return: None
    """
    if not created:
        return None

    if instance.achievement.badge:
        instance.user.badges.add(instance.achievement.badge)
    instance.user.points += instance.achievement.points
    instance.user.save()

    notify.send(instance,
                recipient=instance.user.user,
                verb='was unlocked',
                description='You have unlocked "{0}"'.format(
                    instance.achievement.name),
                url=reverse('view_achievement',
                            achievement_id=instance.achievement.pk))
예제 #13
0
def user_follows(request, pk, format=None):
    check_object_permissions(request, user_follows.cls.permission_classes,
                             User.objects.get(pk=pk))
    if request.method == 'GET':
        serializer = FollowSerializer(request.user, context={request: request})
        return Response(serializer.data)
    elif request.method == 'PUT':
        follows = request.DATA.get('follows')
        request.user.follows.add(*follows)
        serializer = FollowSerializer(request.user)

        # TODO add notification.
        for follow in follows:
            try:
                followed = User.objects.get(pk=follow)
                if request.user != followed:
                    notify.send(request.user,
                                recipient=followed,
                                verb='followed you.')
            except User.DoesNotExist:
                # No such user, skip notification.
                pass

        return Response(serializer.data)
    elif request.method == 'POST':
        follows = request.DATA['follows']
        request.user.follows.remove(*follows)
        serializer = FollowSerializer(request.user)
        return Response(serializer.data)
예제 #14
0
 def test_use_timezone(self):
     from_user = User.objects.create(username="******", password="******", email="*****@*****.**")
     to_user = User.objects.create(username="******", password="******", email="*****@*****.**")
     notify.send(from_user, recipient=to_user, verb='commented', action_object=from_user)
     notification = Notification.objects.get(recipient=to_user)
     delta = datetime.datetime.utcnow().replace(tzinfo=utc) - notification.timestamp
     self.assertTrue(delta.seconds >= 8 * 60 * 59)
예제 #15
0
def like_movil(request):
	id_usuario = request.GET['id_usuario']
	id_nota = request.GET['id_nota']
	le_gusta = request.GET['like']

	usuario = Usuario.objects.get(id = id_usuario)
	nota = Nota.objects.get(id = id_nota)

	if le_gusta == 'true':
		like = LikeNota.objects.get(usuario = usuario, nota = nota)
		like.delete()
	else:
		like = LikeNota()
		like.nota = nota
		like.usuario = usuario
		like.save()

		if (nota.usuario.id != request.user.id):
			key_sesion = session_from_usuario(nota.usuario.id)
			r = redis.StrictRedis(host='localhost', port=6379, db=2)
			mensaje = '{ "session_key": "' + str(key_sesion) + '", "usuario": "' + usuario.username + '", "nota_id": ' + str(nota.id) + ', "nota": "' + nota.titulo + '" }'
			r.publish('me_gusta', mensaje)

			notify.send(
		            like,
		            description= usuario.username + ' le ha gustado ' + nota.titulo,
		            recipient=nota.usuario,
		            target=nota,
		            verb= 'nuevo_like'
		        )

	respuesta = {'usuario': usuario.username, 'titulo': nota.titulo}
	return JsonResponse(respuesta, safe=False)
예제 #16
0
    def deliver(self, recipient, sender, notice_type, extra_context):

        extra_context.update({
            "recipient": recipient,
            "title": ugettext(notice_type.display),
            "description": ugettext(notice_type.description),
        })

        # context = self.default_context()
        messages = self.get_formatted_messages((
            "notice.html",
            "full.html"
        ), notice_type.label, Context(extra_context))

        extra_context.update({
            'body': messages["notice.html"]
        })

        if not sender:
            sender = recipient

        notify.send(
            sender,
            verb=notice_type.label,
            **extra_context)
예제 #17
0
def create_remove_action(sender, author, action, instance, **kwargs):
	tipo = ContentType.objects.get_for_model(instance)
	if str(tipo) == 'ActivitieParent':
		objeto = 'una actividad'
	else:
		objeto = 'un quiz'

	for user in User.objects.all():
		if action == 'add':
			
			notify.send(
				author,
				recipient=user,
				verb=u'modificar',
		        #action_object=instance,
		        description='ha creado '+objeto+' , tu progreso se ha recalculado',
		        target=instance
		        )

		elif action == 'remove':
			
			notify.send(
					author,
					recipient=user,
					verb=u'modificar',
			        #action_object=instance,
			        description= 'ha elimidado '+objeto+' , tu progreso se ha recalculado',
			        #target= instance)
					)
예제 #18
0
    def add_attendee(self, request, pk=None):
        event = self.get_object()
        
        # Get attendee User object
        try:
            userId = request.DATA.get('user_id', None)
            user = User.objects.get(id=userId)
        except User.DoesNotExist:
            raise UserNotFound()
        
        # Create EventAttendee object
        try:
            EventAttendee.objects.create(
                event=event,
                user=user
            )
        except IntegrityError:
            raise EventAlreadyHasAttendee()

        if user != request.user:
            # Generate notification for added user
            notify.send(request.user,
                recipient=user,
                verb='invited',
                action_object=user,
                target=event,
                description='You have been invited to an event'
            )
        
        return Response({})
예제 #19
0
파일: views.py 프로젝트: andyxmai/pickup
def join_quit_game(request):
	#userID = request.user.id
	response = ''
	if request.method == 'POST': 
		game_id = request.POST['game_id']
		print game_id
		
		game = Game.objects.get(id=game_id)
		if request.user in game.users.all():
			game.users.remove(request.user)
			response = 'left'
			verb = request.user.first_name+' '+request.user.last_name+' left '+game.name
			description = '/game/'+str(game.id)
			notify.send(request.user,recipient=game.creator, verb=verb, description=description)
			action.send(request.user, verb="leave game", action_object=game)
		else:
			game.users.add(request.user)
			response = 'joined'
			verb = request.user.first_name+' '+request.user.last_name+' joined '+game.name
			description = '/game/'+str(game.id)
			notify.send(request.user,recipient=game.creator, verb=verb, description=description)
			action.send(request.user, verb="join game", action_object=game)
	
	#return HttpResponse(response)
	return redirect(request.META['HTTP_REFERER'])
예제 #20
0
    def test_unread_count_api(self):
        self.login('to', 'pwd')

        response = self.client.get(
            reverse('notifications:live_unread_notification_count'))
        data = json.loads(response.content.decode('utf-8'))
        self.assertEqual(list(data.keys()), ['unread_count'])
        self.assertEqual(data['unread_count'], 10)

        Notification.objects.filter(recipient=self.to_user).mark_all_as_read()
        response = self.client.get(
            reverse('notifications:live_unread_notification_count'))
        data = json.loads(response.content.decode('utf-8'))
        self.assertEqual(list(data.keys()), ['unread_count'])
        self.assertEqual(data['unread_count'], 0)

        notify.send(self.from_user,
                    recipient=self.to_user,
                    verb='commented',
                    action_object=self.from_user)
        response = self.client.get(
            reverse('notifications:live_unread_notification_count'))
        data = json.loads(response.content.decode('utf-8'))
        self.assertEqual(list(data.keys()), ['unread_count'])
        self.assertEqual(data['unread_count'], 1)
예제 #21
0
def request_delete(request, request_id):
    req = get_object_or_404(Request, pk=request_id)

    if request.user == req.user:
        user = get_object_or_404(CustomUser, pk=req.user.id)

        notify.send(user,
                    recipient=user,
                    verb='Canceled',
                    level='info',
                    action_object=req,
                    description='Ride Request Canceled',
                    target=req.ride)

        notify.send(user,
                    recipient=req.ride.vehicle.user,
                    verb='Canceled',
                    level='info',
                    action_object=req,
                    description='Ride Request Canceled',
                    target=req.ride)

        req.status = 'canceled'
        req.save()
        return redirect('app:requests_user_view', user.id)

    else:
        raise Http404
예제 #22
0
def payment_success(request):
    txn = request.GET.get('tx', None)
    try:
        order = PayPalIPN.objects.get(txn_id=txn)
    except PayPalIPN.DoesNotExist:
        messages.add_message(request, messages.INFO,
                             'We could not locate your transaction')
        return redirect('webstore:review_order')
    else:
        cart = Cart.objects.get(pk=order.invoice)
        if cart.status == CART_STATUS_CHOICES.ORDERED:
            notify.send(
                cart,
                recipient=request.user,
                verb=u'order has been processed',
                action_object=cart,
                description=
                u'We have updated your cart with the wanted product',
            )
            messages.add_message(request, messages.INFO,
                                 'Your transaction was processed')
            return redirect('webstore:order_details', cart_id=cart.id)
        else:
            messages.add_message(request, messages.INFO,
                                 'Your transaction is being processed')
            return redirect('webstore:review_order')
예제 #23
0
def request_ride(request, user_id, ride_id):
    user = get_object_or_404(CustomUser, pk=user_id)
    ride = get_object_or_404(VehicleSharing, pk=ride_id)

    form = RequestForm(request.POST or None)

    if request.user != user:
        raise Http404

    if request.method == "POST":
        if form.is_valid():
            ride_request = form.save(commit=False)
            ride_request.user = user

            ride_request.ride = ride

            ride_request.save()

            notify.send(user,
                        recipient=user,
                        verb='Request',
                        level='info',
                        action_object=ride_request,
                        description='Ride Request is Pending',
                        target=ride)
            notify.send(user,
                        recipient=ride.user,
                        verb='Request',
                        level='info',
                        action_object=ride_request,
                        description='Ride Request From ' + user.username,
                        target=ride)

            return redirect('app:requests_user_view', user_id)
예제 #24
0
파일: views.py 프로젝트: andyxmai/pickup
def comment(request):
	if request.method == 'POST':
		#store comment
		comment_form = CommentForm(request.POST)
		if comment_form.is_valid():
			text = comment_form.cleaned_data['text']
			user_id = comment_form.cleaned_data['user_id']
			game_id = comment_form.cleaned_data['game_id']

			commenter = User.objects.get(id=user_id)
			game = Game.objects.get(id=game_id)

			comment = Comment.objects.create(text=text, commenter=commenter, game=game, timeStamp=datetime.datetime.now() - datetime.timedelta(hours=7))

			for player in game.users.all():
				if commenter != player:
					verb = commenter.first_name+' '+commenter.last_name+' left a comment for '+game.name
					description = '/game/'+str(game.id)
					notify.send(commenter,recipient=player, verb=verb, description=description)

			return redirect('/game/'+str(game.id))
		else:
			return redirect('/')
	else:
		return redirect('/')
예제 #25
0
def apply_coupon(request):
    if request.method == 'POST':
        current_user = request.user
        cart = current_user.active_cart()
        form = DiscountCodeForm(data=request.POST)
        if form.is_valid():
            coupon = cart.apply_discount(form.data['code'])
            if coupon:
                notify.send(
                    coupon,
                    recipient=request.user,
                    verb=u'has been applied',
                    action_object=cart,
                    description=
                    u'We have updated your cart with the wanted product',
                )
                messages.add_message(
                    request, messages.INFO,
                    'Your coupon has been applied to products in promotion')
            else:
                messages.add_message(request, messages.INFO,
                                     'Your coupon is not valid')
        else:
            request.session['form_data'] = request.POST
    return redirect('webstore:review_order')
예제 #26
0
파일: views.py 프로젝트: nsakhala/ipl
def ajax_send_notification(request):
    
    pid=int(request.POST['pId'])
    pob=Player.objects.get(pk=pid)
    if pob.pBid==0:
        pob.pBid=pob.pBaseprice+1000000
    else:
        pob.pBid=pob.pBid+1000000

    pob.save()
    recipients = User.objects.all()
    
    

    for recipient in recipients:
        notify.send(
            request.user,
            recipient=recipient,
            verb=pob.pBid
            
            

        )

    return HttpResponse(json.dumps({"success": True}), content_type="application/json")
예제 #27
0
파일: views.py 프로젝트: andyxmai/pickup
def delete_game(request):
	if request.method == 'POST':
		game_id = request.POST['game_id']
		g = Game.objects.get(id=game_id)
		verb = request.user.first_name+' '+request.user.last_name+' cancelled '+g.name;
		#action.send(request.user,verb=verb,action_object=g)
		receivers = []
		allUsers = g.users.all()
		if len(allUsers) != 0:
			for user in g.users.all():
				print user
				receivers.append(user.username)
				verb = request.user.first_name+' '+request.user.last_name+' cancelled '+g.name
				notify.send(request.user,recipient=user, verb=verb, description='#')

			game_maker = "%s %s" % (g.creator.first_name, g.creator.last_name)
			msg = "Unfortunately, %s has cancelled %s." % (game_maker, g.name)
			subj = "%s Game Cancellation" % (g.name)
			#send_an_email(receivers,subj,msg)

		msg = g.name + ' (' + g.sport.name + ')' + ' was deleted.'
		g.delete()
		messages.success(request, msg)

	return redirect('/home')
예제 #28
0
    def add_member(self, request, pk=None):
        taskforce = self.get_object()
        
        # Get User object from task force's team members; prevents non team members from being added
        try:
            userId = request.DATA.get('user_id', None)
            user = taskforce.team.users.all().get(id=userId)
        except User.DoesNotExist:
            raise UserNotFound()

        # Check if user is already a member
        if taskforce.members.filter(pk=user.pk).count() > 0:
            raise UserAlreadyInTaskForce()
        
        # Add user to members
        taskforce.members.add(user)

        if user != request.user:
            # Generate notification for added user
            notify.send(request.user,
                recipient=user,
                verb='added',
                action_object=user,
                target=taskforce,
                description='You have been added to a taskforce'
            )
        
        return Response({})
예제 #29
0
    def save(self):
        if not self.instance:
            event = Event(
                owner=self.profile,
                title=self.cleaned_data['title'],
                description=self.cleaned_data['description'],
                location=self.cleaned_data['location'],
                start_time=self.cleaned_data['start_time'],
                end_time=self.cleaned_data['end_time'],
                )
        else:
            self.instance.title = self.cleaned_data['title']
            self.instance.description = self.cleaned_data['description']
            self.instance.location = self.cleaned_data['location']
            self.instance.start_time = self.cleaned_data['start_time']
            self.instance.end_time = self.cleaned_data['end_time']
            self.instance.cancelled = self.cleaned_data['cancelled']
            event = self.instance
        event.save()
        if self.cleaned_data['rsvp'] and \
          self.profile.user.username != ANONYMOUS_USERNAME:
              event.rsvps.add(self.profile)
        as_manager = self.cleaned_data['as_manager']
        if as_manager:
            event.as_manager = as_manager
        else:
            event.as_manager = None
        event.save()

        for profile in event.rsvps.all():
            if profile.user == self.profile.user:
                continue
            notify.send(self.profile.user, verb="updated", action=event,
                        recipient=profile.user)
        return event
예제 #30
0
def comment_messages(sender, comment, request, **kwargs):
    """ 添加评论后,增加对应*瓦片*的评论数(冗余字段), 并跳转且作出提示 """
    tile = comment.content_object
    cid = request.REQUEST.get('cid')
    try:
        comment.content_object.after_add_comments()
        tile = comment.content_object
        href = request.REQUEST.get('notify','')
        channel = get_channel(tile)
        if not href:
            href = reverse('axis_tile_view',kwargs={'tile_id': tile.id}) + "?channel=" + channel
    
        #添加一条提醒
        actions = {'title':'新消息','href':href + "#comment_div_" + str(comment.id)}
        
        if tile.creator != request.user:
            notify.send(request.user, verb='新消息', action_object=tile, recipient=tile.creator, actions=actions)
        if cid:
            comment_obj = get_object_or_404(Comment, pk=cid)
            relation = Comment_relation()
            relation.target_object = comment_obj
            relation.action_object = comment
            relation.save()
            if comment_obj.user != request.user:
                notify.send(request.user, verb='新消息', action_object=comment_obj, recipient=comment_obj.user, actions=actions)
    except:
        pass

    if request.user.is_authenticated():
        comment._set_url("http://www." + str(time.mktime(datetime.datetime.now().timetuple())) + ".com")
        comment.save()
예제 #31
0
    def get(self, request):

        user_id = request.GET.get('user')
        resume_buy_result = request.GET.get('status')
        resume_id = request.GET.get('resume_id')
        feed_id = request.GET.get('feed_id')

        resume = ResumeData.objects(id=resume_id)
        resume_works = resume[0].works if resume else None
        latest_job = resume_works[0].position_title if resume_works else "查看详情"

        feed_query = Feed.objects.filter(feed_obj_id=feed_id)
        feed_title = feed_query[0].title if feed_query else None

        if feed_title:
            notify_verb = '简历下载完成:{feed_title}(<a class="c0091fa" href="/resumes/display/{resume_id}/?feed_id={feed_id}">{notify_text}</a>)'.format(
                feed_title=feed_title,
                resume_id=resume_id,
                feed_id=feed_id,
                notify_text=latest_job)
        else:
            notify_verb = '简历下载完成:(<a class="c0091fa" href="/resumes/display/{resume_id}/?feed_id={feed_id}">{notify_text}</a>)'.format(
                resume_id=resume_id, feed_id=feed_id, notify_text=latest_job)
        user_query = User.objects.filter(id=int(user_id))

        if not user_query:
            return JsonResponse({'status': 0})
        if resume_buy_result == '1':
            notify.send(user_query[0],
                        recipient=user_query[0],
                        verb=notify_verb,
                        user_role='hr',
                        notify_type='resume_download_finished')
            return JsonResponse({'status': 'ok'})
        return JsonResponse({'status': 'not notify'})
예제 #32
0
def update_takeaway_on_rating_save(sender, **kwargs):
    if kwargs.get('created',False):
        rating = kwargs.get("instance")
        takeaway = TakeAway.objects.get(pk=rating.takeaway.id)
        rating_value = rating.rating_value
        total_raters = takeaway.total_raters +1
        average_rating = ((takeaway.average_rating * takeaway.total_raters)+rating_value)/total_raters

        takeaway.average_rating = average_rating
        takeaway.total_raters = total_raters
        takeaway.save()

        profile = TakeAwayProfile.objects.get(user=takeaway.user)
        try:
            email_settings = EmailSettings.objects.all().get(user=takeaway.user)
        except EmailSettings.DoesNotExist :
            email_settings = EmailSettings.objects.create(user=takeaway.user)
        message = rating.user.first_name + ' rated takeaway created by ' + takeaway.user.first_name

        notify.send(rating.user,recipient=takeaway.user, verb='RATED',description= message,action_object=takeaway)
        # Giving points to user who rated
        event = PointEvent.objects.get_or_create(event='GOT_RATING',points=5)
        UserEventLog(user=takeaway.user,course_instance=takeaway.courseInstance,session=takeaway.session,event=event[0],points=event[0].points).save()
        # Giving points to user whose takeaway rated
        event = PointEvent.objects.get_or_create(event='GAVE_RATING', points = 5)
        UserEventLog(user=rating.user,course_instance=takeaway.courseInstance,session=takeaway.session,event=event[0],points=event[0].points).save()
예제 #33
0
파일: views.py 프로젝트: hobbes09/ShowCase
def user_follows(request, pk, format=None):
    check_object_permissions(request, user_follows.cls.permission_classes, User.objects.get(pk=pk))
    if request.method == 'GET':
	serializer = FollowSerializer(request.user, context={request: request}) 
	return Response(serializer.data)
    elif request.method == 'PUT':
	follows = request.DATA.get('follows')
	request.user.follows.add(*follows)
	serializer = FollowSerializer(request.user)

	# TODO add notification.
	for follow in follows:
	    try:
		followed = User.objects.get(pk=follow)
		if request.user != followed:
		    notify.send(request.user, recipient=followed, verb='followed you.')
	    except User.DoesNotExist:
		# No such user, skip notification.
		pass

	return Response(serializer.data)
    elif request.method == 'POST':
	follows = request.DATA['follows']
	request.user.follows.remove(*follows)
	serializer = FollowSerializer(request.user)
	return Response(serializer.data)
예제 #34
0
파일: views.py 프로젝트: hobbes09/ShowCase
def user_bookmarks(request, pk, format=None):
    check_object_permissions(request, user_bookmarks.cls.permission_classes, User.objects.get(pk=pk))
    if request.method == 'GET':
	serializer = BookmarkSerializer(request.user, context={request: request}) 
	return Response(serializer.data)
    elif request.method == 'PUT':
	bookmarks = request.DATA.get('bookmarks')
	request.user.bookmarks.add(*bookmarks)
	serializer = BookmarkSerializer(request.user)

	# Add notification.
	for bookmark in bookmarks:
	    try:
		bookmarked = Composition.objects.get(pk=bookmark)
		if request.user != bookmarked.artist:
		    notify.send(request.user, recipient=bookmarked.artist, verb='added to his collection', action_object=bookmarked)
	    except Composition.DoesNotExist:
		# No such user, skip notification.
		pass
	return Response(serializer.data)
    elif request.method == 'POST':
	bookmarks = request.DATA['bookmarks']
	request.user.bookmarks.remove(*bookmarks)
	serializer = BookmarkSerializer(request.user)
	return Response(serializer.data)
예제 #35
0
def notify_on_mention(text, object, user):
    # parsing text looking for mentions (@) to be linked with the object
    # user should always exist
    # TODO : fail-safe perhaps in case a user deletes their profile
    #        at the exact moment that they are mentioned?
    user = User.objects.get(id=user.id)
    mention_list = []
    for username in mention_pattern.findall(force_str(text)):
        mention_list.append(username)

    for mention in mention_list:
        recipient = User.objects.get(username=mention)
        # make sure the recipient exists first, else continue the loop
        # TODO: create front-end search mechanism for users when they start a word with (@)
        if recipient is not None:
            verb = ''
            if isinstance(object, PictureComment):
                verb = u'mentioned you in a comment'
                #content_object = Post.objects.get(id=object.object_pk)
            else:
                verb = u'mentioned you in a post'
                #content_object = object
            notify.send(user,
                        recipient=recipient,
                        verb=verb,
                        action_object=object,
                        description=u'',
                        target=recipient)
        else:
            continue
예제 #36
0
def user_bookmarks(request, pk, format=None):
    check_object_permissions(request, user_bookmarks.cls.permission_classes,
                             User.objects.get(pk=pk))
    if request.method == 'GET':
        serializer = BookmarkSerializer(request.user,
                                        context={request: request})
        return Response(serializer.data)
    elif request.method == 'PUT':
        bookmarks = request.DATA.get('bookmarks')
        request.user.bookmarks.add(*bookmarks)
        serializer = BookmarkSerializer(request.user)

        # Add notification.
        for bookmark in bookmarks:
            try:
                bookmarked = Composition.objects.get(pk=bookmark)
                if request.user != bookmarked.artist:
                    notify.send(request.user,
                                recipient=bookmarked.artist,
                                verb='added to his collection',
                                action_object=bookmarked)
            except Composition.DoesNotExist:
                # No such user, skip notification.
                pass
        return Response(serializer.data)
    elif request.method == 'POST':
        bookmarks = request.DATA['bookmarks']
        request.user.bookmarks.remove(*bookmarks)
        serializer = BookmarkSerializer(request.user)
        return Response(serializer.data)
예제 #37
0
def calculate_health_condition(self, form):
    user = self.request.user
    patient = self.object
    total = 0
    current_health_condition_levels = {
        'nausea_level': patient.nausea_level,
        'headache_level': patient.headache_level,
        'sore_throat_level': patient.sore_throat_level,
        'abdominal_pain_level': patient.abdominal_pain_level,
        'constipation_level': patient.constipation_level,
        'lack_of_appetite_level': patient.lack_of_appetite_level,
        'sleepiness_level': patient.sleepiness_level,
        'insomnia_level': patient.insomnia_level
    }
    for level in current_health_condition_levels:
        total += int(current_health_condition_levels[level])
        if int(current_health_condition_levels[level]) >= 4:
            notify.send(user,
                        recipient=user,
                        verb='%s\'s %s is %s' %
                        (patient.get_full_name(), level,
                         current_health_condition_levels[level]),
                        level='warning')
    if total >= 25:
        notify.send(user,
                    recipient=user,
                    verb='%s\'s health condition is urgent (Level: %s)' %
                    (patient.get_full_name(), total),
                    level='danger')
예제 #38
0
def handle_invitation_request(request, invitation_request_id):
    '''This view handles the answering to an invitation, bringing together declining and accepting to one function'''
    explorer = get_object_or_404(get_user_model(),
                                 pk=request.POST.get('to_explorer_id'))
    assert explorer == request.user
    invitation_request = InvitationRequest.objects.get(
        pk=invitation_request_id)  # Ugly way of filtering down
    if 'accept' in request.POST:
        invitation_request.experience.explorers.add(explorer)
        if invitation_request.experience.gallery:
            invitation_request.experience.gallery.explorers.add(explorer)
        messages.success(
            request,
            'You are now an explorer of {0}. You can edit aspects of the experience, upload narratives, and add your own photos.'
            .format(invitation_request.experience))
        notify.send(
            sender=explorer,
            recipient=invitation_request.experience.author,
            verb='has accepted your request and is now a part your experience',
            target=invitation_request.experience)
        invitation_request.delete()
        return redirect(
            reverse('experiences.views.index',
                    args=(invitation_request.experience.id, )))
    else:
        messages.success(
            request,
            'You have declined the invitation to the experience {0}.'.format(
                invitation_request.experience))
        invitation_request.delete()
    return redirect(request.META.get('HTTP_REFERER'))
예제 #39
0
def continuous_and_one_per_day(resv, exclude_segs=False):
    ''' All days within a reservation must be consecutive. 
        Multi-activity reservation are allowed, but each activity type must be consecutive. 
        '''
    prev_end_date = dt.date(1900, 1, 1)
    segs = resv.get_future_blocking_segs_no_sb()

    if exclude_segs:
        segs = segs.exclude(id__in=exclude_segs)
    for seg in segs.order_by('start_date'):
        if prev_end_date != dt.date(1900, 1, 1):
            delta = seg.start_date - prev_end_date
            print seg
            print delta.days
            if delta.days > 1:
                error_str = u'All days within a reservation must be consecutive.'
                notify.send(seg, recipient=resv.owner, verb=error_str)
                return False
            if delta.days < 1:
                notify.send(seg,
                            recipient=resv.owner,
                            verb=u'Only one ranch may be booked per day')
                return False

        prev_end_date = seg.end_date
    return True
예제 #40
0
def upload_photo(request, gallery_id):
    gallery = get_object_or_404(Gallery, pk=gallery_id)
    if request.method == 'POST':
        form = GalleryPhotoForm(request.POST, request.FILES)
        if form.is_valid():
            photo = form.save(commit=False)
            photo.author = request.user
            photo.title_slug = slugify(photo.title)
            photo.is_public = True
            photo.gallery = gallery
            photo.save()
            if 'feature' in request.POST.keys():
                gallery.featured_photo = photo
                gallery.save()
            messages.success(request, 'Your photo was successfully uploaded')
            for comrade in gallery.explorers.exclude(id=request.user.id):
                notify.send(sender=request.user,
                            recipient=comrade,
                            target=photo,
                            verb='has uploaded a new photo')
            return HttpResponseRedirect('/photologue/gallery/{0}/'.format(
                gallery.id))
    else:
        form = GalleryPhotoForm()
    return render(request, 'photologue/upload_photo.html', {
        'form': form,
        'gallery': gallery
    })
예제 #41
0
def live_tester(request):
    notify.send(sender=request.user, recipient=request.user, verb='you loaded the page')

    return render(request, 'test_live.html', {
        'unread_count': request.user.notifications.unread().count(),
        'notifications': request.user.notifications.all()
    })
예제 #42
0
파일: models.py 프로젝트: meletakis/collato
    def add(self, user, status=None, symmetrical=False):
        """
        Add a relationship from one user to another with the given status,
        which defaults to "following".

        Adding a relationship is by default asymmetrical (akin to following
        someone on twitter).  Specify a symmetrical relationship (akin to being
        friends on facebook) by passing in :param:`symmetrical` = True

        .. note::

            If :param:`symmetrical` is set, the function will return a tuple
            containing the two relationship objects created
        """
        if not status:
            status = RelationshipStatus.objects.following()

        relationship, created = Relationship.objects.get_or_create(
            from_user=self.instance,
            to_user=user,
            status=status,
            site=Site.objects.get_current())

        ####### NOTIFICATION #############
        notify.send(self.instance, recipient=user, verb=status)
        ###############################

        pending_status = RelationshipStatus.objects.get(name="Pending")

        if symmetrical:
            user.relationships.remove(self.instance, pending_status, False)
            return (relationship,
                    user.relationships.add(self.instance, status, False))
        else:
            return relationship
예제 #43
0
 def test_disable_timezone(self):
     from_user = User.objects.create(username="******", password="******", email="*****@*****.**")
     to_user = User.objects.create(username="******", password="******", email="*****@*****.**")
     notify.send(from_user, recipient=to_user, verb='commented', action_object=from_user)
     notification = Notification.objects.get(recipient=to_user)
     delta = timezone.now() - notification.timestamp
     self.assertTrue(delta.seconds < 60)
예제 #44
0
def ajax_upload(request):
    gallery = get_object_or_404(Gallery, pk=request.POST.get('gallery_id'))
    assert request.user in gallery.explorers.all()
    if request.method == 'POST':
        form = GalleryPhotoForm(request.POST, request.FILES)
        if form.is_valid():
            photo = form.save(commit=False)
            photo.author = request.user
            photo.title_slug = slugify(photo.title)
            photo.is_public = True
            photo.gallery = gallery
            photo.save()
            if 'feature' in request.POST.keys():
                gallery.featured_photo = photo
                gallery.save()
            for comrade in gallery.explorers.exclude(id=request.user.id):
                notify.send(sender=request.user,
                            recipient=comrade,
                            target=photo,
                            verb='has uploaded a new photo')
            data = {
                'html':
                render_to_string(
                    'photologue/snippets/photo_dash.html', {
                        'photo': photo,
                        'user': request.user,
                        'STATIC_URL': settings.STATIC_URL
                    })
            }
            return HttpResponse(json.dumps(data))
        else:
            # Here's the problem with the images not uploading properly
            return HttpResponse('Please fill out the form correctly')
    # Return nothing for failure??
    return HttpResponse('api')
예제 #45
0
 def test_use_timezone(self):
     from_user = User.objects.create(username="******", password="******", email="*****@*****.**")
     to_user = User.objects.create(username="******", password="******", email="*****@*****.**")
     notify.send(from_user, recipient=to_user, verb='commented', action_object=from_user)
     notification = Notification.objects.get(recipient=to_user)
     delta = timezone.now().replace(tzinfo=utc) - localtime(notification.timestamp, pytz.timezone(settings.TIME_ZONE))
     self.assertTrue(delta.seconds < 60)
예제 #46
0
파일: tests.py 프로젝트: dan0712/django-app
 def test_use_timezone(self):
     from_user = self.from_user
     to_user = self.to_user
     notify.send(from_user, recipient=to_user, verb='commented', action_object=from_user)
     notification = Notification.objects.get(recipient=to_user)
     delta = now().replace(tzinfo=utc) - localtime(notification.timestamp, pytz.timezone(settings.TIME_ZONE))
     self.assertTrue(delta.seconds < 60)
예제 #47
0
 def setUp(self):
     self.u = User.objects.create_user(username="******", password="******")
     self.client.login(username="******", password="******")
     notify.send(self.u,
                 verb="tested",
                 action_object=self.u,
                 recipient=self.u)
예제 #48
0
 def reject_loan_application(self, rejecter, comment=None):
     self.status = self.REJECTED
     self.save()
     notify.send(rejecter.member, recipient=self.member.user, verb='rejected',
         description='Your loan application was rejected', target=self, level='fail')
     if comment:
         self.give_feedback_on_loan_application(comment=comment)
예제 #49
0
파일: forms.py 프로젝트: naderm/farnsworth
    def save(self, note=None):
        instance = self.cleaned_data["pk"]
        workshifter = instance.workshifter or instance.liable
        pool_hours = workshifter.pool_hours.get(pool=instance.pool)

        # Check if the shift was previously verified or marked as blown
        _undo_verify_blown(instance, pool_hours)
        instance.save(update_fields=["verifier", "closed"])
        pool_hours.save(update_fields=["standing"])

        instance.logs.add(
            ShiftLogEntry.objects.create(
                person=self.profile,
                entry_type=ShiftLogEntry.UNVERIFY,
                note=note,
            )
        )

        if self.profile != workshifter:
            notify.send(
                self.profile.user,
                verb="unverified",
                action_object=instance,
                recipient=workshifter.user,
            )

        return instance
예제 #50
0
파일: forms.py 프로젝트: naderm/farnsworth
    def save(self, note=None):
        instance = self.cleaned_data["pk"]
        workshifter = instance.workshifter or instance.liable
        pool_hours = workshifter.pool_hours.get(pool=instance.pool)

        # Check if the shift was previously verified or marked as blown
        _undo_verify_blown(instance, pool_hours)
        instance.save(update_fields=["blown", "closed"])
        pool_hours.save(update_fields=["standing"])

        instance.logs.add(
            ShiftLogEntry.objects.create(
                person=self.profile,
                entry_type=ShiftLogEntry.UNBLOWN,
                note=note,
            )
        )

        # Notify the workshifter as well as the workshift manager
        targets = []
        if self.profile != instance.workshifter:
            targets.append(instance.workshifter.user)
        for manager in instance.pool.managers.all():
            if manager.incumbent and manager.incumbent.user != self.profile.user:
                targets.append(manager.incumbent.user)
        for target in targets:
            notify.send(
                self.profile.user,
                verb="marked as unblown",
                action_object=instance,
                recipient=target,
            )

        return instance
예제 #51
0
파일: views.py 프로젝트: meletakis/collato
def add_developer(request):
    form = UserProfileForm()
    
    if request.method == 'POST':
        form = UserProfileForm(request.POST)
        if form.is_valid():
			#user_profile = form.save()
			data = form.cleaned_data
			site = Site.objects.get_current()
			new_user = RegistrationProfile.objects.create_inactive_user(data['username'] , data['email'],data['password'], site , send_email = False)
			userprofileobj = UserProfile(user = new_user, role_id=11, displayName = data['username'], thumbnailURL= '/static/main/img/user.png ')
			userprofileobj.save()

			s_admins = User.objects.filter(is_superuser = 1)
			for s_admin in s_admins:
				notify.send(new_user, recipient=s_admin, verb='signed_up' )

			return HttpResponseRedirect('/')
    


    return render(request, "userprofiles/registration.html", {
        'form': form, 
        'action' : 'Create'
    })
예제 #52
0
 def test_disable_timezone(self):
     from_user = User.objects.create(username="******", password="******", email="*****@*****.**")
     to_user = User.objects.create(username="******", password="******", email="*****@*****.**")
     notify.send(from_user, recipient=to_user, verb='commented', action_object=from_user)
     notification = Notification.objects.get(recipient=to_user)
     delta = timezone.now() - notification.timestamp
     self.assertTrue(delta.seconds < 60)
예제 #53
0
 def test_use_timezone(self):
     from_user = User.objects.create(username="******", password="******", email="*****@*****.**")
     to_user = User.objects.create(username="******", password="******", email="*****@*****.**")
     notify.send(from_user, recipient=to_user, verb='commented', action_object=from_user)
     notification = Notification.objects.get(recipient=to_user)
     delta = timezone.now().replace(tzinfo=utc) - localtime(notification.timestamp,pytz.timezone(settings.TIME_ZONE))
     self.assertTrue(delta.seconds < 60)
예제 #54
0
파일: tests.py 프로젝트: dan0712/django-app
 def test_disable_timezone(self):
     from_user = self.from_user
     to_user = self.to_user
     notify.send(from_user, recipient=to_user, verb='commented', action_object=from_user)
     notification = Notification.objects.get(recipient=to_user)
     delta = now() - notification.timestamp
     self.assertTrue(delta.seconds < 60)
예제 #55
0
 def setUp(self):
     self.message_count = 1
     self.from_user = User.objects.create_user(username="******", password="******", email="*****@*****.**")
     self.to_user = User.objects.create_user(username="******", password="******", email="*****@*****.**")
     self.to_user.is_staff = True
     self.to_user.save()
     for i in range(self.message_count):
         notify.send(self.from_user, recipient=self.to_user, verb='commented', action_object=self.from_user, url="/learn/ask-a-pro/q/test-question-9/299/", other_content="Hello my 'world'")
예제 #56
0
 def setUp(self):
     self.message_count = 10
     self.from_user = User.objects.create_user(username="******", password="******", email="*****@*****.**")
     self.to_user = User.objects.create_user(username="******", password="******", email="*****@*****.**")
     self.to_user.is_staff = True
     self.to_user.save()
     for i in range(self.message_count):
         notify.send(self.from_user, recipient=self.to_user, verb='commented', action_object=self.from_user)
예제 #57
0
 def system_notify(cls, user, notify_type):
     '''
     param: notify_type
         welcome: 欢迎加入聘宝
     '''
     verb = cls.SYSTEM_NOTIFY[notify_type]
     notify.send(user, recipient=user, verb=verb)
     return True
예제 #58
0
def noti(sender, post, content):
    receiver_list = post.joined.all()
    msg = '[' + post.title + '] ' + content
    for receiver in receiver_list:
        if receiver != sender:
            notify.send(sender, recipient=receiver, verb=msg)
    if post.initiator != sender:
        notify.send(sender, recipient=post.initiator, verb=msg)