Python notifications.signals.notify.send() Examples

The following are 30 code examples of notifications.signals.notify.send(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module notifications.signals.notify , or try the search function .
Example #1
Source File: teams.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def invite_members(request, team_id):
    """Return a team edit view, or handle the form submission."""
    team = get_object_or_404(Team, pk=team_id)

    if team.owner_id is None or team.owner_id != request.user.id:
        raise SuspiciousOperation(_('User is not the owner of the team'))

    if request.method == 'POST':
        form = TeamInviteForm(request.POST, team=team)
        if form.is_valid():
            to_invite = form.cleaned_data['members']
            invites = [TeamRequest(team=team, inviter=request.user, invitee=x) for x in to_invite]
            TeamRequest.objects.bulk_create(invites)
            for user in to_invite:
                notify.send(request.user, recipient=user, actor=request.user, verb='invite', action_object=team, target=user)
            messages.success(request, _('Invited {count} members to the team').format(count=len(to_invite)))
            return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
    else:
        form = TeamInviteForm(team=team)
    return render(request, 'teams/invite.html', context={
        'team': team,
        'form': form
    }) 
Example #2
Source File: models.py    From srvup-membership with MIT License 6 votes vote down vote up
def new_user_receiver(sender, instance, created, *args, **kwargs):
	if created:
		new_profile, is_created = UserProfile.objects.get_or_create(user=instance)
		#print new_profile, is_created
		notify.send(instance, 
					recipient=MyUser.objects.get(username='jmitchel3'), #admin user
					verb='New user created.')
		# merchant account customer id -- stripe vs braintree
	try:
		merchant_obj = UserMerchantId.objects.get(user=instance)
	except:
		new_customer_result = braintree.Customer.create({
				"email": instance.email
			})
		if new_customer_result.is_success:
			merchant_obj, created = UserMerchantId.objects.get_or_create(user=instance)
			merchant_obj.customer_id = new_customer_result.customer.id
			merchant_obj.save()
			print """Customer created with id = {0}""".format(new_customer_result.customer.id)
		else:
			print "Error: {0}".format(new_customer_result.message)
			messages.error(request, "There was an error with your account. Please contact us.")

		
		# send email for verifying user email 
Example #3
Source File: notifications_helpers.py    From govready-q with GNU General Public License v3.0 6 votes vote down vote up
def issue_notification(acting_user, verb, target, recipients='WATCHERS', **notification_kwargs):
    # Create a notification *from* acting_user *to*
    # all users who are watching target.
    from notifications.signals import notify
    if recipients == 'WATCHERS':
        recipients = target.get_notification_watchers()
    for user in recipients:
        # Don't notify the acting user about an
        # action they took.
        if user == acting_user:
            continue

        # Create the notification.
        # TODO: Associate this notification with an organization?
        notify.send(
            acting_user, verb=verb, target=target,
            recipient=user,
            **notification_kwargs) 
Example #4
Source File: views.py    From instiapp-api with GNU Affero General Public License v3.0 6 votes vote down vote up
def create_test_notification(cls, request):
        user = request.user

        # Throttle test notification
        test_notifications = request.user.notifications.filter(verb='Test notification').first()

        if test_notifications is not None:
            last_notif_timestamp = test_notifications.timestamp
            if last_notif_timestamp > timezone.now() - timedelta(minutes=15):
                return Response({
                    "message": "Too soon",
                    "detail": "Last test notification was sent within last 15 minutes."
                }, status=429)

        notify.send(user, recipient=user, verb='Test notification')
        return Response(status=200) 
Example #5
Source File: handlers.py    From django-project with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def commented_handler(instance, comment, **kwargs):
    for follow in Follow.objects.get_follows(instance):
        notify.send(instance.author,
                    recipient=follow.user,
                    actor=instance.author,
                    verb='commented',
                    action_object=comment,
                    description=comment.comment[:50]+'...',
                    target=instance)

    from django.contrib.contenttypes.models import ContentType
    from django.contrib.admin.models import LogEntry, ADDITION
    from django.utils.encoding import force_unicode
    LogEntry.objects.log_action(
        user_id         = instance.author.pk,
        content_type_id = ContentType.objects.get_for_model(comment).pk,
        object_id       = comment.pk,
        object_repr     = force_unicode(comment),
        action_flag     = ADDITION
    )

# connect the signal 
Example #6
Source File: handlers.py    From django-project with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def workflow_task_handler_creator(verb):
    """
    """
    print('REG workflow_task_handler_creator::handler', verb)
    def handler(instance, *args, **kwargs):
        print('workflow_task_handler_creator::handler', verb)
        follow_obj = instance.project if verb=='created' else instance
        for follow in Follow.objects.get_follows(follow_obj):
            notify.send(instance.author,
                        recipient=follow.user,
                        actor=instance.author,
                        verb=verb,
                        action_object=instance,
                        description='',
                        target=instance.project)
    if not hasattr(workflow_task_handler_creator, 'instances'):
        workflow_task_handler_creator.instances = []
    workflow_task_handler_creator.instances.append(handler)
    return handler 
Example #7
Source File: models.py    From srvup-rest-framework with Apache License 2.0 6 votes vote down vote up
def new_user_receiver(sender, instance, created, *args, **kwargs):
	if created:
		new_profile, is_created = UserProfile.objects.get_or_create(user=instance)
		#print new_profile, is_created
		notify.send(instance, 
					recipient=MyUser.objects.get(username='jmitchel3'), #admin user
					verb='New user created.')
		# merchant account customer id -- stripe vs braintree
	try:
		merchant_obj = UserMerchantId.objects.get(user=instance)
	except:
		new_customer_result = braintree.Customer.create({
				"email": instance.email
			})
		if new_customer_result.is_success:
			merchant_obj, created = UserMerchantId.objects.get_or_create(user=instance)
			merchant_obj.customer_id = new_customer_result.customer.id
			merchant_obj.save()
			print """Customer created with id = {0}""".format(new_customer_result.customer.id)
		else:
			print "Error: {0}".format(new_customer_result.message)
			messages.error(request, "There was an error with your account. Please contact us.")

		
		# send email for verifying user email 
Example #8
Source File: views.py    From Collaboration-System with GNU General Public License v2.0 6 votes vote down vote up
def notify_subscribe_unsubscribe(user, target, type):
    verb=''
    target_url=''
    if isinstance(target, Community):
        target_url="community_view"
        if type == 'subscribe':
            verb='Welcome to the community'
        elif type == 'unsubscribe':
            verb = 'You have successfully unsubscribed from the community and can no longer contribute. Your earlier contributions to the community will remain.'
    elif isinstance(target, Group):
        target_url="group_view"
        if type == 'subscribe':
            verb = 'Welcome to the group'
        elif type == 'unsubscribe':
            verb = 'You have successfully unsubscribed from the group and can no longer contribute. Your earlier contributions to the group will remain.'

    notify.send(sender=user, recipient=user,
                verb=verb, target=target, target_url=target_url, sender_url="display_user_profile", sender_url_name=user.username ) 
Example #9
Source File: teams.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def decide_invitation(request, invite_id):
    invite = get_object_or_404(TeamRequest, pk=invite_id)
    team = invite.team

    if team.owner_id is None or team.owner_id != request.user.id:
        raise SuspiciousOperation(_('User is not the owner of the team'))
    elif 'accept' in request.POST:
        invite.team.members.add(invite.invitee)
        invite.team.save()
        notify.send(request.user, recipient=invite.invitee, actor=request.user, verb='accept', action_object=team, target=invite.invitee)
        messages.success(request, _('Added {name} to the team').format(name=invite.invitee.username))
    elif 'reject' in request.POST:
        notify.send(request.user, recipient=invite.invitee, actor=request.user, verb='reject', action_object=team, target=invite.invitee)
        messages.success(request, _('Ignored {name}\'s team membership request').format(name=invite.invitee.username))
    else:
        return HttpResponseBadRequest(_('POST request must include either "{accept}" or "{reject}"').format(accept='accept', reject='reject'))

    invite.delete()
    return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,))) 
Example #10
Source File: teams.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def revoke_membership(request, team_id, member_id):
    team = get_object_or_404(Team, pk=team_id)
    user = get_object_or_404(User, pk=member_id)

    if team.owner_id is None or team.owner_id != request.user.id:
        raise SuspiciousOperation(_('User is not the owner of the team'))
    elif user == team.owner:
        raise SuspiciousOperation(_('Cannot remove the owner from the team'))
    elif not team.invitation_required:
        raise SuspiciousOperation(_('Cannot remove user from teams that don\'t require an invitation'))

    team.members.remove(user)
    team.save()
    notify.send(request.user, recipient=user, actor=request.user, verb='remove', action_object=team, target=user)
    messages.success(request, _('Removed {name} from team').format(name=user.username))
    return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,))) 
Example #11
Source File: teams.py    From open-synthesis with GNU General Public License v3.0 6 votes vote down vote up
def join_team(request, team_id):
    team = get_object_or_404(Team, pk=team_id)

    if team.members.filter(id=request.user.id).exists():
        raise SuspiciousOperation(_('User is already a member of the team'))
    elif TeamRequest.objects.filter(invitee=request.user, inviter__isnull=False, team=team).exists() or not team.invitation_required:
        team.members.add(request.user)
        team.save()
        TeamRequest.objects.filter(invitee=request.user, team=team).delete()
        messages.success(request, _('Joined team {name}').format(name=team.name))
        return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
    elif TeamRequest.objects.filter(invitee=request.user, team=team).exists():
        return HttpResponseBadRequest(_('User already has a membership request with the team'))
    else:
        TeamRequest.objects.create(invitee=request.user, team=team)
        if team.owner:
            notify.send(request.user, recipient=team.owner, actor=request.user, verb='request_membership', target=team)
        messages.success(request, _('Requested invitation to team {name}').format(name=team.name))
        return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,))) 
Example #12
Source File: test_notifications.py    From open-synthesis with GNU General Public License v3.0 5 votes vote down vote up
def test_can_clear_notifications(self):
        """Test that a user can clear notifications via POST request."""
        notify.send(self.other, recipient=self.user, actor=self.other, verb='said hello!')
        notify.send(self.user, recipient=self.other, actor=self.user, verb='said hello!')
        self.assertGreater(self.user.notifications.unread().count(), 0)
        self.login()
        response = self.client.post(reverse('openach:clear_notifications'), data={
            'clear': 'clear',
        })
        self.assertEqual(response.status_code, 302)
        self.assertEqual(self.user.notifications.unread().count(), 0)
        # make sure we didn't clear someone else's notifications
        self.assertGreater(self.other.notifications.unread().count(), 0) 
Example #13
Source File: handlers.py    From django_blog with MIT License 5 votes vote down vote up
def comment_handler(sender, instance, created, **kwargs):
    if created:
        recipient = ADMINS.exclude(id=instance.user.id)
        if not instance.parent is None:
            recipient = recipient.exclude(id=instance.parent.user.id)
            if recipient.count() > 0:
                notify.send(instance.user, recipient=recipient,
                            verb='回复了 %s' % instance.parent.user_name,
                            action_object=instance,
                            target=instance.post,
                            description=instance.content)
                if SEND_NOTIFICATION_EMAIL:
                    email_handler.delay(user2id(*recipient))
            if not instance.user_name == instance.parent.user_name:
                notify.send(instance.user, recipient=instance.parent.user, verb='@了你',
                            action_object=instance,
                            target=instance.post,
                            description=instance.content)
                if SEND_NOTIFICATION_EMAIL:
                    email_handler.delay(user2id(instance.parent.user))
        else:
            if recipient.count() > 0:
                notify.send(instance.user, recipient=recipient, verb='发表了评论',
                            action_object=instance,
                            target=instance.post,
                            description=instance.content)
                if SEND_NOTIFICATION_EMAIL:
                    email_handler.delay(user2id(*recipient)) 
Example #14
Source File: placement_blog_chore.py    From instiapp-api with GNU Affero General Public License v3.0 5 votes vote down vote up
def handle_entry(entry, body, url):
    """Handle a single entry from a feed."""

    # Try to get an entry existing
    guid = entry['id']
    db_entry = BlogEntry.objects.filter(guid=guid).first()
    new_added = False

    # Reuse if entry exists, create new otherwise
    if not db_entry:
        db_entry = BlogEntry(guid=guid, blog_url=url)
        new_added = True

    # Fill the db entry
    if 'title' in entry:
        db_entry.title = entry['title']
    if 'content' in entry and entry['content']:
        db_entry.content = handle_html(entry['content'][0]['value'])
    if 'link' in entry:
        db_entry.link = entry['link']
    if 'published' in entry:
        db_entry.published = parse(entry['published'])

    db_entry.save()

    # Send notification to mentioned people
    if new_added and db_entry.content:
        # Send notifications to followers
        if body is not None:
            users = User.objects.filter(id__in=body.followers.filter(active=True).values('user_id'))
            notify.send(db_entry, recipient=users, verb="New post on " + body.name)

        # Send notifications for mentioned users
        roll_nos = [p for p in profile_fetcher.get_roll() if p and p in db_entry.content]
        if roll_nos:
            users = User.objects.filter(profile__roll_no__in=roll_nos)
            notify.send(db_entry, recipient=users, verb="You were mentioned in a blog post") 
Example #15
Source File: notifications.py    From instiapp-api with GNU Affero General Public License v3.0 5 votes vote down vote up
def news_saved(instance, created, **kwargs):
    """Notify users when a followed body adds new news."""
    if created and instance.body and instance.notify:
        users = User.objects.filter(id__in=instance.body.followers.filter(active=True).values('user_id'))
        notify.send(instance, recipient=users, verb=instance.body.name + " added a new news article") 
Example #16
Source File: tasks.py    From instiapp-api with GNU Affero General Public License v3.0 5 votes vote down vote up
def notify_upd_event(pk):
    """Notify users about event updation."""
    setUp()
    instance = Event.objects.filter(id=pk).first()
    if not instance:
        return

    users = User.objects.filter(id__in=instance.followers.filter(active=True).values('user_id'))
    notify.send(instance, recipient=users, verb=instance.name + " was updated") 
Example #17
Source File: tasks.py    From instiapp-api with GNU Affero General Public License v3.0 5 votes vote down vote up
def notify_new_event(pk):
    """Notify users about event creation."""
    setUp()
    instance = Event.objects.filter(id=pk).first()
    if not instance:
        return

    for body in instance.bodies.all():
        users = User.objects.filter(id__in=body.followers.filter(active=True).values('user_id'))
        notify.send(
            instance,
            recipient=users,
            verb=body.name + " has added a new event"
        ) 
Example #18
Source File: tests.py    From instiapp-api with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_pt_notifications(self):
        """Test notifications for placement blog (Incomplete - only serializer)"""
        # Create dummy
        entry = BlogEntry.objects.create(
            title="BlogEntry1", blog_url='https://test.com', published=timezone.now())

        # Notify
        notify.send(entry, recipient=self.user, verb="TEST")

        # Get notifications
        url = '/api/notifications'
        response = self.client.get(url)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(len(response.data), 1)
        self.assertEqual(response.data[0]['actor']['title'], entry.title) 
Example #19
Source File: handlers.py    From django-project with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def unfollow_handler(follower, followee, **kwargs):
    """
    """
    notify.send(follower,
                recipient=follower,
                actor=follower,
                verb='stopped following',
                action_object=followee,
                description='',
                target=getattr(followee, 'project', None))

# connect the signal 
Example #20
Source File: handlers.py    From django-project with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def follow_handler(follower, followee, **kwargs):
    """
    """
    notify.send(follower,
                recipient=follower,
                actor=follower,
                verb='started following',
                action_object=followee,
                description='',
                target=getattr(followee, 'project', None)) 
Example #21
Source File: test_profile.py    From open-synthesis with GNU General Public License v3.0 5 votes vote down vote up
def test_private_notifications(self):
        """Test that the profile page shows up to 5 notifications."""
        for x in range(0, 10):
            notify.send(self.other, recipient=self.user, actor=self.other, verb='said hello {}'.format(x))
        self.login()
        response = self.client.get(reverse('profile', args=(self.user.id,)))
        self.assertContains(response, 'said hello', status_code=200, count=5) 
Example #22
Source File: handlers.py    From django-easy-comment with MIT License 5 votes vote down vote up
def comment_handler(sender, instance, created, **kwargs):
    if created:
        recipient = ADMINS.exclude(id=instance.user.id)
        if instance.parent is not None:
            recipient = recipient.exclude(id=instance.parent.user.id)
            if recipient.count() > 0:
                notify.send(instance.user, recipient=recipient,
                            verb='回复了 %s' % instance.parent.user.username,
                            action_object=instance,
                            target=instance.content_object,
                            description=instance.content)
                if SEND_NOTIFICATION_EMAIL:
                    email_handler(*recipient)
            if not instance.user.username == instance.parent.user.username:
                notify.send(instance.user, recipient=instance.parent.user, verb='@了你',
                            action_object=instance,
                            target=instance.content_object,
                            description=instance.content)
                if SEND_NOTIFICATION_EMAIL:
                    email_handler(instance.parent.user)
        else:
            if recipient.count() > 0:
                notify.send(instance.user, recipient=recipient, verb='发表了评论',
                            action_object=instance,
                            target=instance.content_object,
                            description=instance.content)
                if SEND_NOTIFICATION_EMAIL:
                    email_handler(*recipient) 
Example #23
Source File: views.py    From Collaboration-System with GNU General Public License v2.0 5 votes vote down vote up
def notify_update_course_state(user, course, action):
    if CommunityCourses.objects.filter(course=course).exists():
        commcourses = CommunityCourses.objects.get(course=course)
        membership = CommunityMembership.objects.get(user=user, community=commcourses.community.pk)
        sender_rolename = membership.role.name

        comm_admin_list = []
        comm_publisher_list = []
        comm_pub_admin = []
        comm_admin_list = get_comm_list(commcourses.community,'community_admin',course)
        comm_publisher_list = get_comm_list(commcourses.community,'publisher',course)
        comm_pub_admin = comm_admin_list + comm_publisher_list

        if action == 'publishable':
            notify.send(sender=user, recipient=comm_pub_admin,
                        verb='This course has been made publishable', target=course,
                        target_url="course_view", sender_url="display_user_profile",
                        sender_url_name=user.username, sender_rolename=sender_rolename)

        elif action == 'publish':
            notify.send(sender=user, recipient=course.created_by,
                        verb='Your course has been published', target=course,
                        target_url="course_view", sender_url="display_user_profile",
                        sender_url_name=user.username, sender_rolename=sender_rolename)

            notify.send(sender=user, recipient=comm_pub_admin,
                        verb='Course has been published', target=course,
                        target_url="course_view", sender_url="display_user_profile",
                        sender_url_name=user.username, sender_rolename=sender_rolename) 
Example #24
Source File: views.py    From Collaboration-System with GNU General Public License v2.0 5 votes vote down vote up
def notify_edit_course(user, course, verb):
    if(user != course.created_by):
        try:
            commcourses = CommunityCourses.objects.get(course=course)
            membership = CommunityMembership.objects.get(user=user, community=commcourses.community.pk)
            sender_rolename = membership.role.name
            notify.send(sender=user, verb=verb, recipient=course.created_by,
                        target=course, target_url="course_view",
                        sender_url='display_user_profile',
                        sender_url_name=user.username,
                        sender_rolename=sender_rolename)
        except CommunityMembership.DoesNotExist:
            errormessage = 'You are not a member of the community' 
Example #25
Source File: views.py    From Collaboration-System with GNU General Public License v2.0 5 votes vote down vote up
def notify_edit_article(user, article, current_state):

    if(user != article.created_by):
        verb=""
        role=""
        if CommunityArticles.objects.filter(article=article).exists():
            comm = CommunityArticles.objects.get(article=article)
            membership = CommunityMembership.objects.get(user=user, community=comm.community.pk)
            role = membership.role.name
            if role == 'publisher':
                verb="Publisher edited your article"
            if(role=="community_admin"):
                verb="Admin edited your article"

        else:
            grp = GroupArticles.objects.get(article=article)
            if current_state == 'private' :
                membership = GroupMembership.objects.get(user=user, group=grp.group.pk)
                role = membership.role.name
            elif current_state == 'visible':
                comm = CommunityGroups.objects.get(group=grp.group)
                membership = CommunityMembership.objects.get(user=user, community=comm.community.pk)
                role = membership.role.name

            if role == 'publisher':
                if current_state == 'private' :
                    verb="Group publisher edited your article"
                elif current_state == 'visible' :
                    verb = "Community publisher edited your article"
            elif (role == "group_admin"):
                verb = "Group admin edited your article"
            elif (role == 'community_admin') :
                verb = "Community admin edited your article"

        if role == 'author':
            verb="Your article got edited"

        notify.send(sender=user, verb=verb, recipient=article.created_by,
                    target=article,
                    target_url="article_view", sender_url='display_user_profile',
                    sender_url_name=user.username) 
Example #26
Source File: notifications.py    From open-synthesis with GNU General Public License v3.0 5 votes vote down vote up
def notify_followers(board, actor, verb, action_object):
    """Notify board followers of that have read permissions for the board."""
    for follow in board.followers.all().select_related('user'):
        if follow.user != actor and board.can_read(follow.user):
            notify.send(actor, recipient=follow.user, actor=actor, verb=verb, action_object=action_object, target=board) 
Example #27
Source File: comment.py    From eoj3 with MIT License 4 votes vote down vote up
def send_notification(request, **kwargs):
  def get_parent_user(comment):
    return XtdComment.objects.get(pk=comment['parent_id']).user

  comment = kwargs['comment']
  if comment['content_type'].name in ('blog', 'problem', 'contest'):
    recipient = None
    target = None
    verb = 'replied on'
    if comment['content_type'].name == 'blog':
      target = comment['content_object']
      recipient = target.author
      if comment['parent_id']:
        recipient = get_parent_user(comment)
    elif comment['content_type'].name == 'contest':
      target = contest = comment['content_object']
      if comment['parent_id']:
        recipient = get_parent_user(comment)
        verb = 'replied in'
      elif is_contest_manager(comment.user, contest):
        recipient = list(map(lambda x: x.user, contest.contestparticipant_set.all()))
        verb = 'posted a notification in'
      else:
        recipient = contest.managers.all()
        verb = 'asked a question in'
    elif comment['content_type'].name == 'problem':
      if comment['parent_id']:
        target = comment['content_object']
        recipient = get_parent_user(comment)
      else:
        return

    level = 'info'
    if comment['content_type'].name == 'contest':
      level = 'warning'

    if recipient and recipient != comment['user']:
      notify.send(sender=comment['user'],
                  recipient=recipient,
                  verb=verb,
                  level=level,
                  target=target) 
Example #28
Source File: actions.py    From django-idcops with Apache License 2.0 4 votes vote down vote up
def release(request, queryset):
    action = sys._getframe().f_code.co_name
    action_name = "释放机柜"
    rack_ids = [id for id in queryset.values_list('id', flat=True)]
    # fix: unknown your action: The QuerySet value
    if Online.objects.filter(rack_id__in=rack_ids).exists():
        mesg = "选择的机柜中仍有在线设备,无法释放"
        return mesg

    queryset = queryset.filter(actived=True)
    if request.POST.get('post'):
        for obj in queryset:
            o = copy.deepcopy(obj)
            if obj.client and obj.client.onlinenum() == 0:
                verb = "客户 {} 没有在线设备, 是否终止".format(force_text(obj.client))
                notify_user.send(
                    request.user,
                    recipient=request.user,
                    target=obj,
                    verb=verb,
                )

            obj.actived = False
            obj.client = None
            obj.cpower = 0
            obj.style = None
            obj.status = None
            obj.operator = request.user
            obj.tags.clear()

            if obj.jnum() != 0:
                verb = "机柜 {} 还有跳线存在, 请回收".format(force_text(obj))
                notify_user.send(
                    request.user,
                    recipient=request.user,
                    target=obj,
                    verb=verb,
                )

            obj.save()
            from idcops.lib.tasks import get_related_client_name
            diffs = diff_dict(model_to_dict(o), model_to_dict(obj))
            log_action(
                user_id=request.user.pk,
                content_type_id=get_content_type_for_model(obj, True).pk,
                object_id=obj.pk,
                action_flag=action_name,
                message=json.dumps(list(diffs.keys())),
                content=json.dumps(diffs),
                related_client=get_related_client_name(o)
            )
        return None
    context = construct_context(request, queryset, action, action_name)
    return TemplateResponse(request, 'base/base_confirmation.html', context) 
Example #29
Source File: views.py    From Collaboration-System with GNU General Public License v2.0 4 votes vote down vote up
def notify_update_role(sender, user, target, current_role):
    target_url=''
    previous_role=''

    if isinstance(target, Community) and CommunityMembership.objects.filter(user=user, community=target).exists():
        membership = CommunityMembership.objects.get(user=user, community=target.pk)
        target_url="community_view"
        previous_role = membership.role.name

    elif GroupMembership.objects.filter(user=user, group=target).exists():
        membership = GroupMembership.objects.get(user=user, group=target.pk)
        target_url = "group_view"
        previous_role = membership.role.name

    if current_role == 'publisher':
        if previous_role == 'author':
            notify.send(sender=sender, verb='Congratulations! Your role has been upgraded from Author to Publisher', recipient=user, target=target,
                        target_url=target_url, sender_url='display_user_profile', sender_url_name=sender.username)
        elif previous_role == 'community_admin' or previous_role == 'group_admin' :
            notify.send(sender=sender, verb='Your role has been changed from Admin to Publisher', recipient=user,
                        target=target,
                        target_url=target_url, sender_url='display_user_profile', sender_url_name=sender.username)

    elif current_role == 'author':
        if previous_role == 'publisher':
            notify.send(sender=sender, verb='Your role has been changed from Publisher to Author', recipient=user,
                        target=target,
                        target_url=target_url, sender_url='display_user_profile', sender_url_name=sender.username)

        elif previous_role == 'community_admin' or previous_role == 'group_admin':
            notify.send(sender=sender, verb='Your role has been changed from Admin to Author', recipient=user,
                        target=target,
                        target_url=target_url, sender_url='display_user_profile', sender_url_name=sender.username)

    elif current_role == 'community_admin' or current_role == 'group_admin':
        if previous_role == 'publisher':
            notify.send(sender=sender, verb='Congratulations! Your role has been upgraded from Publisher to Admin', recipient=user,
                        target=target,
                        target_url=target_url, sender_url='display_user_profile', sender_url_name=sender.username)

        elif previous_role == 'author':
            notify.send(sender=sender, verb='Congratulations! Your role has been upgraded from Author to Admin', recipient=user,
                        target=target,
                        target_url=target_url, sender_url='display_user_profile', sender_url_name=sender.username) 
Example #30
Source File: actions.py    From django-idcops with Apache License 2.0 4 votes vote down vote up
def removeup(request, queryset):
    action = sys._getframe().f_code.co_name
    action_name = "取消下架"
    exclude = queryset.filter(rack__actived=False)
    if exclude.exists():
        mesg = "有设备所在机柜未使用, 无法取消下架"
        return mesg

    if request.POST.get('post'):
        for obj in queryset:
            o = copy.deepcopy(obj)
            obj.actived = True
            obj.status = 'online'
            obj.operator = request.user
            lastunits = copy.deepcopy(obj.units.all())
            lastpdus = copy.deepcopy(obj.pdus.all())
            ucan_recovery = False not in [u.actived for u in lastunits]
            pcan_recovery = False not in [p.actived for p in lastpdus]
            if ucan_recovery:
                obj.units.all().update(actived=False, operator=obj.operator)
            else:
                verb = "无法恢复 {} 的U位".format(force_text(obj))
                notify_user.send(
                    request.user,
                    recipient=request.user,
                    target=obj,
                    verb=verb,
                )
                obj.units.clear()
            if pcan_recovery:
                obj.pdus.all().update(actived=False, operator=obj.operator)
            else:
                obj.pdus.clear()
            obj.save()
            diffs = diff_dict(model_to_dict(o), model_to_dict(obj))
            message = json.dumps(list(diffs.keys()))
            old_units = [force_text(u) for u in lastunits]
            old_pdus = [force_text(p) for p in lastpdus]
            diffs.update({'last_units': old_units, 'last_pdus': old_pdus})
            content = json.dumps(diffs)
            log_action(
                user_id=request.user.pk,
                content_type_id=get_content_type_for_model(obj, True).pk,
                object_id=obj.pk, action_flag=action_name,
                message=message, content=content
            )
        return None
    context = construct_context(request, queryset, action, action_name)
    return TemplateResponse(request, 'base/base_confirmation.html', context)