def test_auto_unfollow_on_edited_project(self): # first change project that more users follow the project project_settings_changed = project_settings.copy() project_settings_changed['developer'] = (self.user2.pk) project_settings_changed["manager"] = (self.user.pk, self.user3.pk) self.client.post( reverse('project:edit', kwargs={'project': project_settings_changed['name_short']}), project_settings_changed) # first remove a manager again project_settings_changed["manager"] = (self.user.pk) self.client.post( reverse('project:edit', kwargs={'project': project_settings_changed['name_short']}), project_settings_changed) self.assertNotIn(self.user3, followers(self.project)) self.assertIn(self.user, followers(self.project)) # second remove a developer again del project_settings_changed["developer"] self.client.post( reverse('project:edit', kwargs={'project': project_settings_changed['name_short']}), project_settings_changed) self.assertNotIn(self.user2, followers(self.project))
def handle(self, *args, **options): self.stdout.write('\n Creating Post/Answers for testing: \n\n') consultants = Consultant.objects.all() for circle in Circle.objects.all(): users = followers(circle) if len(users) < 5: for consultant in set( random.choices(consultants, k=random.randint(2, 10))): circle.add_user(consultant.user) users = followers(circle) for i in range(random.randint(2, 10)): user = random.choices(users, k=1)[0] post = Post.objects.create_circle_post( user_from=user, circle=circle, title=' '.join(faker.words()), description=faker.text(), tags=random.choices(Keyword.objects.all(), k=random.randint(2, 6)), ) for consultant in set( random.choices(consultants, k=random.randint(2, 10))): post.see(consultant.user) for consultant in set( random.choices(consultants, k=random.randint(2, 10))): post.see(consultant.user) post.reply(consultant.user, faker.text()) self.stdout.write('\n Finish!! \n\n')
def feeds_fanout_posted(action): """Populate users feeds from the given action.""" # Define list of processed users (to prevent multiple timeline # entries for the same post) processed_users = [] def add_to_timeline(user, action): user.feed_entries.create( category='timeline', action=action, ) log.debug('Adding post activity %i to user %i timeline' % (action.id, user.id)) processed_users.append(user) # Add to the timeline of the post owner add_to_timeline(action.actor, action) # Find followers of user for follower in models_actstream.followers(action.actor): add_to_timeline(follower, action) for tag in action.action_object.tags.all(): for follower in models_actstream.followers(tag): if follower in processed_users: log.debug('Skip adding post to timeline, it exists already') continue add_to_timeline(follower, action)
def Company_Detail (request,pk = "", slug = ""): try: company = Company.objects.get(pk = pk) except Company.DoesNotExist: raise Http404 if request.method == "POST": if 'follow' in request.POST: follow_id = request.POST.get('follow', False) if follow_id: try: company_id = Company.objects.get(pk=follow_id) follow(request.user, company_id) #request.user.get_profile().applicant except Company.DoesNotExist: return render(request, 'company_detail.html', {'id': company,'follow':False }) else: unfollow_id = request.POST.get('unfollow', False) if unfollow_id: try: company_id = Company.objects.get(pk=unfollow_id) unfollow(request.user, company_id) #request.user.get_profile().applicant except Company.DoesNotExist: return render(request, 'company_detail.html', {'id': company,'follow':True }) if followers(company): print followers(company) return render(request, 'company_detail.html', {'id': company,'follow':False }) return render(request, 'company_detail.html', {'id': company,'follow':True })
def test_followers_with_flag(self): self.assertEqual(list(followers(self.another_group, flag='liking')), [self.user4]) self.assertEqual(list(followers(self.another_group, flag='watching')), [self.user4]) self.assertEqual(list(followers(self.user1, flag='liking')), [self.user4]) self.assertEqual(list(followers(self.user3, flag='blacklisting')), [self.user4])
def test_auto_follow_on_created_project(self): # create a second project with the second user as developer project2_settings = { 'name': 'test_project2', 'name_short': 'tp2', 'description': 'test2', 'developer': (self.user2.pk), } self.client.post(reverse('project:create'), project2_settings) newProject = Project.objects.filter( name_short=project2_settings['name_short']).first() self.assertIn(self.user, followers(newProject)) self.assertIn(self.user2, followers(newProject))
def listeFollowers(request): if not request.user.is_permacat: return render(request, "notPermacat.html") listeArticles = [] for art in Article.objects.all(): suiveurs = followers(art) if suiveurs: listeArticles.append({"titre": art.titre, "url": art.get_absolute_url(), "followers": suiveurs, }) for art in Projet.objects.all(): suiveurs = followers(art) if suiveurs: listeArticles.append({"titre": art.titre, "url": art.get_absolute_url(), "followers": suiveurs, }) return render(request, 'listeFollowers.html', {"listeArticles":listeArticles})
def handle_follow_unfollow_on_archive_unarchive(sender, instance, *args, **kwargs): try: old = Issue.objects.get(project=instance.project, number=instance.number) except ObjectDoesNotExist: return # unfollow/follow in archive/unarchive (activity stream) if not old.archived and instance.archived: for user in followers(instance.project): unfollow_issue(user, instance) if old.archived and not instance.archived: for user in followers(instance.project): follow_issue(user, instance)
def get_context_data(self, **kwargs): """Adds visible requests and followers to project context""" context = super(ProjectDetailView, self).get_context_data(**kwargs) project = context["object"] user = self.request.user context["sidebar_admin_url"] = reverse( "admin:project_project_change", args=(project.pk,) ) visible_requests = project.requests.get_viewable(user).select_related( "agency__jurisdiction__parent__parent", "composer__user__profile" ) context["visible_requests"] = visible_requests.get_public_file_count(limit=6) context["visible_requests_count"] = visible_requests.count() articles = project.articles.get_published().prefetch_related( Prefetch("authors", queryset=User.objects.select_related("profile")) ) context["articles"] = articles[:3] context["articles_count"] = articles.count() context["followers"] = followers(project) context["contributors"] = project.contributors.select_related("profile") context["user_is_experimental"] = ( user.is_authenticated and user.profile.experimental ) context["newsletter_label"] = ( "Subscribe to the project newsletter" if not project.newsletter_label else project.newsletter_label ) context["newsletter_cta"] = ( "Get updates delivered to your inbox" if not project.newsletter_cta else project.newsletter_cta ) context["user_can_edit"] = project.editable_by(user) return context
def get_user_followers(self): ''' people that follow self.request.user ''' follower = followers(self.request.user)[:6] return follower
def to_premium_handle(bet_group_id): # from premium: there is no need to auto unfollow the bet group. When the existing subscriptions expire # the auto unfollow will happen. try: bet_group = BetTag.objects.get(id=bet_group_id) except BetTag.DoesNotExist as e: logger.debug('%s', e) return owner = bet_group.owner owner_followers = followers(owner) if not owner_followers: return # owner_followers_ids = owner_followers.values_list('id', flat=True) subject = 'Your tipster {} offers a new Premium service!'.format( owner.username) html_template = 'bet_tagging/to_premium.html' text_template = 'bet_tagging/to_premium.txt' context = { 'domain': Site.objects.get_current().domain, 'bet_group': bet_group } to_list = [] recipient_variables = {} for user in owner_followers: to_list.append(user.email) recipient_values = { "username": user.username, "id": user.id, } recipient_variables[user.email] = recipient_values recipient_variables = json.dumps(recipient_variables) res = emails.utils.mailgun_send(to_list, subject, text_template, html_template, context, recipient_variables) logger.debug("send mailgun mails function returned %s", res)
def bet_group_create_handle(cls, bet_group_id): """ When a new Free bet group is created, new notification subscription entries are created for the existing user followers """ logger.debug('bet_group_create_handle...') try: bet_group = BetTag.objects.get(id=bet_group_id) except Exception as e: logger.warning('%s', e) return if not bet_group.type == BetTag.free: return user_followers = followers(bet_group.owner) if not user_followers: return notification_subscriptions = [] for user in user_followers: try: notification_subscription = cls.objects.create( user=user, bet_group=bet_group) notification_subscriptions.append(notification_subscription) except Exception as e: logger.error('%s', e) logger.debug('%s notification_subscriptions were created', len(notification_subscriptions)) return notification_subscriptions
def projets_suivis(request, slug): projet = Projet.objects.get(slug=slug) suiveurs = followers(projet) return render(request, "blog/projets_suivis.html", { 'suiveurs': suiveurs, "projet": projet })
def run(self, *args, **kwargs): try: answer = Answer.objects.get(pk=kwargs.get('answer_pk')) except Answer.DoesNotExist: return action = kwargs.get('action') post = answer.post context = {} if post.qa_session: qa_team = post.qa_sessions.first() following = qa_team.get_available_users(search='') context['project'] = post.project serializer = AnswerPostSwarmSerializer(answer, context=context) else: if post.is_project: context['project'] = post.project following = followers(post) serializer = AnswerPostSerializer(answer, context=context) for follower in following: if follower != answer.created_by: class UserReq: user = follower context['request'] = UserReq notifications.send_notifications( get_topic_by_object(answer), action, answer.__class__.__name__.lower(), follower.uuid, serializer.data)
def feeds_fanout_replied(action): """Distribute notifications about a comment being replied to.""" # Fan out notification to parent Comment followers for follower in models_actstream.followers( action.action_object.parent_comment): if action.actor == follower: # If the reply author is the same as the parent comment author log.debug('Skipping notification generation for comment owner') continue log.debug('Generating notification for user %i about reply %i' % (follower.id, action.action_object.id)) follower.feed_entries.create(action=action) # Email notification content_name = truncatechars(action.action_object.entity.title, 15) content_text = truncatechars(action.action_object.content, 25) reply_context = dillo.views.emails.CommentOrReplyContext( subject='Your comment has a new reply!', own_name=follower.profile.first_name_guess or follower.username, own_profile_absolute_url=follower.profile.absolute_url, action_author_name=action.actor.profile.first_name_guess or action.actor.username, action_author_absolute_url=action.actor.profile.absolute_url, content_name=content_name, content_absolute_url=action.action_object.absolute_url, content_text=content_text, ).as_dict send_notification_mail( f'Your comment has a new reply!', follower, template='reply', context=reply_context, )
def send_action_mail(action): users = set(filter(lambda x: x.userprofile.notify_by_email, reduce(lambda res, x: (res | set(followers(x))) if x else res, [action.actor, action.action_object, action.target], set()))) q = None if isinstance(action.action_object, Task): q = Q(userprofile__notify_about_new_tasks=True) if isinstance(action.action_object, Service): q = Q(userprofile__notify_about_new_services=True) if q: users |= set(User.objects.filter(q & Q(userprofile__notify_by_email=True))) connection = get_connection(fail_silently=True) site = Site.objects.get(pk=1) messages = [] emails = set() if hasattr(action.actor, 'email'): emails.add(action.actor.email) for user in users: if user.email in emails: continue messages.append(create_action_email( Context({'action': action, 'user': user, 'site': site}), user.email, connection)) emails.add(user.email) if isinstance(action.action_object, django_comments.get_model()) and action.action_object.parent \ and not action.action_object.parent.user and action.action_object.parent.email not in emails: messages.append(create_action_email( Context({'action': action, 'user_name': action.action_object.parent.name, 'site': site}), action.action_object.parent.email, connection)) connection.send_messages(messages)
def profile(request, username): user = get_object_or_404(User, username__iexact = username) if request.is_ajax(): queryset = Message.objects.get_conversation_between(user, request.user) paginator = Paginator(queryset, 10) page = request.GET.get('page') try: message_list = paginator.page(page) except PageNotAnInteger: raise Http404 except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. message_list = paginator.page(paginator.num_pages) return render_to_response('umessages/conversation.html',{'message_list': message_list}) else: extra_context = dict() extra_context['followers'] = ActStream.followers(user) extra_context['followings'] = ActStream.following(user) extra_context['recipe_list'] = list(user.recipe_set.all().only('name', 'cover_image', 'did_num', 'like_num', 'date', 'view_num')) extra_context['favourite_list'] = list(user.get_profile().favourite_recipes.all().only('name', 'cover_image', 'did_num', 'like_num', 'date', 'view_num')) extra_context['form'] = MugshotForm() extra_context['public_messages'] = list(Message.objects.get_public_messages(to_user = user)) extra_context['recommends'] = list(recommendations.recommendRecipeForUser(user.id, 10)) extra_context['did_recipe_list'] = list(DidRecipe.objects.filter(user = user).select_related('recipe').only('image', 'date', 'recipe__name')) response = profile_detail(request, username, extra_context = extra_context) return response
def lireConversation(request, destinataire): conversation = getOrCreateConversation(request.user.username, destinataire) messages = Message.objects.filter(conversation=conversation).order_by("date_creation") message_defaut = None id_panier = request.GET.get('panier') if id_panier: id_destinataire = Profil.objects.get(username=destinataire).id message_defaut = Panier.objects.get(id=id_panier).get_message_demande(int(id_destinataire)) id_produit = request.GET.get('produit') if id_produit: message_defaut = Produit.objects.get(id=id_produit).get_message_demande() form = MessageForm(request.POST or None, message=message_defaut) if form.is_valid(): message = form.save(commit=False) message.conversation = conversation message.auteur = request.user conversation.date_dernierMessage = message.date_creation conversation.dernierMessage = "(" + str(message.auteur) + ") " + str(message.message[:50]) + "..." conversation.save() message.save() url = conversation.get_absolute_url() action.send(request.user, verb='envoi_salon_prive', action_object=conversation, url=url, group=destinataire, description="a envoyé un message privé à " + destinataire) profil_destinataire = Profil.objects.get(username=destinataire) if profil_destinataire in followers(conversation): sujet = "Permacat - quelqu'un vous a envoyé une message privé" message = request.user.username + " vous a envoyé un message privé. Vous pouvez y accéder en suivant ce lien : http://www.perma.cat" + url send_mail(sujet, message, "*****@*****.**", [profil_destinataire.email, ], fail_silently=False,) return redirect(request.path) return render(request, 'lireConversation.html', {'conversation': conversation, 'form': form, 'messages_echanges': messages, 'destinataire':destinataire})
def on_comment_create(sender, instance, created, **kwargs): comment = instance if created: notify.send( comment.user, recipient=followers(comment.post), verb="wrote a comment", action_object=comment, target=comment.post, ) notify.send( comment.user, recipient=followers(comment.user), verb="wrote a comment", action_object=comment, )
def profile_related_list(request, username, relation): "Render the list of a users folllowers or who the user is following" profile = get_object_or_404(Profile, user__username__iexact=username) user = profile.user # get a queryset of users described by this relationship if relation == 'followers': related_users = models.followers(user) elif relation == 'following': related_users = models.following(user) paginator = Paginator(related_users, 20) page = request.GET.get('page') try: related_users = paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. related_users = paginator.page(1) except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. related_users = paginator.page(paginator.num_pages) return render(request, "accounts/account_profile_related.html", { 'user': user, 'profile': profile, 'related_users': related_users, })
def get_context_data(self, **kwargs): """Adds visible requests and followers to project context""" context = super(ProjectDetailView, self).get_context_data(**kwargs) project = context['object'] user = self.request.user context['sidebar_admin_url'] = reverse('admin:project_project_change', args=(project.pk, )) context['visible_requests'] = ( project.requests.get_viewable(user).select_related( 'agency__jurisdiction__parent__parent', 'composer__user__profile', ).get_public_file_count()) context['followers'] = followers(project) context['articles'] = ( project.articles.get_published().prefetch_related( Prefetch('authors', queryset=User.objects.select_related('profile')))) context['contributors'] = project.contributors.select_related( 'profile') context['user_is_experimental'] = user.is_authenticated( ) and user.profile.experimental context['newsletter_label'] = ('Subscribe to the project newsletter' if not project.newsletter_label else project.newsletter_label) context['newsletter_cta'] = ('Get updates delivered to your inbox' if not project.newsletter_cta else project.newsletter_cta) context['user_can_edit'] = project.editable_by(user) return context
def get_queryset(self): order_by = self.request.GET.get('o') order_dir = self.request.GET.get('d') # Get ordering field name if order_by == 'name': order = 'user__first_name' else: order = 'rank_pts' # Get ordering direction (asc/desc) if order_dir == 'asc': prefix = '' else: prefix = '-' qs = super(UserListView, self).get_queryset().filter( user__is_active=True).exclude(user__pk=1) # Filter results for single location only if self.location is not None: qs = qs.filter( user__pk__in=[x.pk for x in followers(self.location)]) # Allow simple search functionality search_query = self.request.GET.get('q') if search_query is not None: qs = qs.filter(Q(user__first_name__icontains=search_query) | Q(user__last_name__icontains=search_query)) return qs.order_by("{}{}".format(prefix, order))
def feeds_fanout_commented(action): # Fan out notification to Post followers for follower in models_actstream.followers(action.action_object.entity): if action.actor == follower: log.debug('Skipping notification generation post owner') continue log.debug('Generating notification for user %i about comment %i' % (follower.id, action.action_object.id)) follower.feed_entries.create(action=action) # Email notification content_name = truncatechars(action.action_object.entity.title, 15) content_text = truncatechars(action.action_object.content, 25) comment_context = dillo.views.emails.CommentOrReplyContext( subject='Your post has a new comment!', own_name=follower.profile.first_name_guess or follower.username, own_profile_absolute_url=follower.profile.absolute_url, action_author_name=action.actor.profile.first_name_guess or action.actor.username, action_author_absolute_url=action.actor.profile.absolute_url, content_name=content_name, content_absolute_url=action.action_object.absolute_url, content_text=content_text, ).as_dict send_notification_mail( f'Your post "{content_name}" has a new comment', follower, template='comment', context=comment_context, )
def handle(self, *args, **kwargs): user_id = kwargs.get('user_id') if not user_id: users = User.objects.all() else: users = User.objects.filter(id=user_id) for user in users: follower_users = followers(user) following_users = following(user, User) if follower_users: num_followers = len(follower_users) else: num_followers = 0 # initially default value was None instead of 0, so update the db with 0 if following_users: num_following = len(following_users) else: num_following = 0 user.basic_stats.num_followers = num_followers user.basic_stats.num_following = num_following user.basic_stats.save() self.stdout.write('Done!\n')
def user_actions(self, user): '''Provides action interfaces for users''' is_owner = self.created_by(user) can_follow = user.is_authenticated() and not is_owner is_following = user in followers(self) is_admin = user.is_staff kwargs = { 'jurisdiction': self.jurisdiction.slug, 'jidx': self.jurisdiction.pk, 'idx': self.pk, 'slug': self.slug } return [ Action(test=True, link=reverse('foia-clone', kwargs=kwargs), title='Clone', desc='Start a new request using this one as a base', class_name='primary'), Action(test=can_follow, link=reverse('foia-follow', kwargs=kwargs), title=('Unfollow' if is_following else 'Follow'), class_name=('default' if is_following else 'primary')), Action( test=self.has_perm(user, 'flag'), title='Get Help', action='flag', desc= u'Something broken, buggy, or off? Let us know and we’ll fix it', class_name='failure modal'), Action(test=is_admin, title='Contact User', action='contact_user', desc=u'Send this request\'s owner an email', class_name='modal'), ]
def activity(request): if request.is_ajax(): queryset = models.user_stream(request.user) paginator = Paginator(queryset, 10) page = request.GET.get('page') try: action_list = paginator.page(page) except PageNotAnInteger: raise Http404 except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. action_list = paginator.page(paginator.num_pages) return render_to_response('actstream/update_list.html',{ 'action_list': action_list, }) else: queryset = models.user_stream(request.user) paginator = Paginator(queryset, 10) try: action_list = paginator.page(1) except PageNotAnInteger: raise Http404 except EmptyPage: # If page is out of range (e.g. 9999), deliver last page of results. action_list = paginator.page(paginator.num_pages) return render(request, 'actstream/update.html', { 'ctype': ContentType.objects.get_for_model(User), 'actor': request.user, 'action_list': action_list, 'following': models.following(request.user), 'followers': models.followers(request.user), 'recommends': recommendations.recommendRecipeForUser(request.user.id, 10) })
def get_queryset(self): order_by = self.request.GET.get('o') order_dir = self.request.GET.get('d') # Get ordering field name if order_by == 'name': order = 'user__first_name' else: order = 'rank_pts' # Get ordering direction (asc/desc) if order_dir == 'asc': prefix = '' else: prefix = '-' qs = super(UserListView, self).get_queryset().filter( user__is_active=True).exclude(user__pk=1) # Filter results for single location only if self.location is not None: qs = qs.filter( user__pk__in=[x.pk for x in followers(self.location)]) # Allow simple search functionality search_query = self.request.GET.get('q') if search_query is not None: qs = qs.filter( Q(user__first_name__icontains=search_query) | Q(user__last_name__icontains=search_query)) return qs.order_by("{}{}".format(prefix, order))
def get_followers(self): order = self.request.GET.get('order') qs = User.objects.filter(pk__in=[x.pk for x in followers(self.object)]) if order == 'abc': return qs.order_by('first_name', 'last_name') else: return qs.order_by('-profile__rank_pts')
def lireConversation(request, destinataire): conversation = getOrCreateConversation(request.user.username, destinataire) messages = Message.objects.filter(conversation=conversation).order_by("date_creation") form = MessageForm(request.POST or None) if form.is_valid(): message = form.save(commit=False) message.conversation = conversation message.auteur = request.user conversation.date_dernierMessage = message.date_creation conversation.dernierMessage = ("(" + str(message.auteur) + ") " + str(strip_tags(message.message).replace('&nspb',' ')))[:96] + "..." conversation.save() message.save() url = conversation.get_absolute_url() action.send(request.user, verb='envoi_salon_prive', action_object=conversation, url=url, group=destinataire, description="a envoyé un message privé à " + destinataire) profil_destinataire = Profil.objects.get(username=destinataire) if profil_destinataire in followers(conversation): sujet = "PacteACVI - quelqu'un vous a envoyé une message privé" message = request.user.username + " vous a envoyé un message privé ://pacteacvi.herokuapp.com" + url send_mail(sujet, message, "*****@*****.**", [profil_destinataire.email, ], fail_silently=False,) return redirect(request.path) return render(request, 'lireConversation.html', {'conversation': conversation, 'form': form, 'messages_echanges': messages, 'destinataire':destinataire})
def get_followers_list(request,user_pk): """List of users who follow user_pk""" print "getting followers_list" connection = User.objects.get(pk=user_pk) cur_user = connection node = request.user followers_of_user = followers(User.objects.get(pk=user_pk)) node_follows = following(node) followers_list = [] for connected in followers_of_user: if connected in node_follows: followers_list.append({"followed_by_connection":connected, "followed_by_me":"Following"}) else: followers_list.append({"followed_by_connection":connected, "followed_by_me":"Not Following"}) is_cur_user = False if request.user == connection: is_cur_user = True ctx = { "followers_list": followers_list, 'cur_user':cur_user, 'followed_user' : connection.first_name, 'is_cur_user' : is_cur_user, } print 'followers' print followers_list return render(request,"profile/user_connections.html",ctx)
def articles_suivis(request, slug): article = Article.objects.get(slug=slug) suiveurs = followers(article) return render(request, 'blog/articles_suivis.html', { 'suiveurs': suiveurs, "article": article, })
def profile(request,id): user=User.objects.get(id=id) profile=Profile.objects.get(user=user) images=Image.objects.filter(user=user) following1=following(user) followers1=followers(profile) return render(request, 'grams/profile.html',{"user":user,"profile": profile, 'images':images,'following':following1,'followers':followers1})
def followers(self, request, pk): queryset = Profile.objects.all() profile = get_object_or_404(queryset, pk=pk) user = profile.user targets = followers(user) profiles = [_.profile for _ in targets] serializer = MinimalProfileSerializer(profiles, many=True) return Response(serializer.data)
def send_notification(sender, instance, created, **kwargs): if not created: return recipients = actstream_models.followers(instance.actor) if instance.action_object: recipients += actstream_models.followers(instance.action_object) if instance.target: recipients += actstream_models.followers(instance.target) unique_recipients = set(recipients) for recipient in unique_recipients: n = Notification(recipient=recipient, action=instance) n.save()
def to_representation(self, obj): return_obj = super(UserSerializer, self).to_representation(obj) followers_count = len(followers(obj)) following_count = len(following(obj)) new_obj = {"following": following_count, "followers": followers_count} return_obj.update(new_obj) return return_obj
def user_follows(sender, instance, created, **kwargs): # Update users counters instance.user.profile.total_following =\ len(following(instance.user, User)) instance.user.profile.save() instance.follow_object.profile.total_followers =\ len(followers(instance.follow_object)) instance.follow_object.profile.save()
def user_deletes_recipe(sender, instance, using, **kwargs): # Update users counters instance.user.profile.total_following =\ len(following(instance.user, User)) instance.user.profile.save() instance.follow_object.profile.total_followers =\ len(followers(instance.follow_object)) instance.follow_object.profile.save()
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) tag_name = self.kwargs['tag_name'] context['tag_name'] = tag_name # TODO(fsiddi) Refactor tag_name as tag.name context['tag'] = get_object_or_404(Tag, name=tag_name) context['tag_followers_count'] = len(followers(context['tag'])) context['query_url'] = reverse('embed_posts_list_tag', kwargs={'tag_name': tag_name}) return context
def followers(request, content_type_id, object_id): """ Creates a listing of ``User``s that follow the actor defined by ``content_type_id``, ``object_id``. """ ctype = get_object_or_404(ContentType, pk=content_type_id) actor = get_object_or_404(ctype.model_class(), pk=object_id) return render_to_response(('actstream/followers.html', 'activity/followers.html'), { 'followers': models.followers(actor), 'actor': actor }, context_instance=RequestContext(request))
def my_suggestions(self, request): # Big method. We'll start with followers, then have follows of follows user = request.user users_following_me = [u for u in followers(user) if not Follow.objects.is_following(user, u)] followers_of_follows = [] follows_of_follows = [] # Now look at the users that we're following for user_i_follow in following(user): for follow_of_follow in following(user_i_follow): if follow_of_follow.id != user.id and not Follow.objects.is_following(user, follow_of_follow): follows_of_follows += [follow_of_follow] for follower_of_follow in followers(user_i_follow): if follower_of_follow.id != user.id and not Follow.objects.is_following(user, follower_of_follow): followers_of_follows += [follower_of_follow] target_profiles = set([_.profile for _ in users_following_me + follows_of_follows + followers_of_follows]) print(target_profiles) serializer = MinimalProfileSerializer(target_profiles, many=True) return Response(serializer.data)
def handle_action(action_id): action = Action.objects.get(pk=action_id) if action.public: users = followers(action.target) users = [user for user in users if user_wants_notification(user, action)] notifications = [Notification(user=user, action=action) for user in users] Notification.objects.bulk_create(notifications) else: user = action.actor Notification.objects.create(user=user, action=action)
def followers(request, content_type_id, object_id): """ Creates a listing of ``User``s that follow the actor defined by ``content_type_id``, ``object_id``. """ ctype = get_object_or_404(ContentType, pk=content_type_id) instance = get_object_or_404(ctype.model_class(), pk=object_id) return render(request, 'actstream/followers.html', context={ 'followers': models.followers(instance), 'actor': instance })
def get_profile(request, profile_name): user = get_object_or_404(User, username=profile_name) user_d = user_to_dict(get_object_or_404(User, username=profile_name)) user_d["following"] = following(user) user_d["followers"] = followers(user) user_d["actions"] = [dict(verb=x.verb, object=x.action_object and user_to_dict(x.action_object), when=int(x.timestamp.strftime("%s")) * 1000, data=x.data) for x in actor_stream(user)[:3]] return user_d
def post(self, request, username, format=None): user_to_follow = get_object_or_404(User, username=username) following_list = following(request.user, User) if user_to_follow in following_list: unfollow(request.user, user_to_follow) data = {'message': 'User unfollowed successfully'} else: follow(request.user, user_to_follow) data = {'message': 'User followed successfully'} data['count'] = len(followers(user_to_follow)) return Response(data)
def comment_action(sender, comment=None, target=None, **kwargs): action.send(comment.user, verb=u'commented', action_object=comment, target=comment.content_object) target = comment.content_object from actstream.models import followers notify_list = followers(target) if hasattr(target, 'user'): notify_list.append(target.user) notification.send(notify_list, "comment_added", { "comment": comment.text, "commenter": comment.user, "target": target })
def followers(request, content_type_id, object_id): """ Creates a listing of ``User``s that follow the actor defined by ``content_type_id``, ``object_id``. """ ctype = get_object_or_404(ContentType, pk=content_type_id) instance = get_object_or_404(ctype.model_class(), pk=object_id) return render_to_response( "actstream/followers.html", {"followers": models.followers(instance), "actor": instance}, context_instance=RequestContext(request), )
def test_followers_following(self): response = self.get('actstream_followers', self.user_ct.pk, self.user2.pk) self.assertTemplateUsed(response, 'actstream/followers.html') self.assertEqual(response.context['user'], self.user1) self.assertQSEqual(response.context['followers'], models.followers(self.user2)) response = self.get('actstream_following', self.user2.pk) self.assertTemplateUsed(response, 'actstream/following.html') self.assertEqual(response.context['user'], self.user2) self.assertQSEqual(response.context['following'], models.following(self.user2))
def followers(request, content_type_id, object_id): """ Creates a listing of ``User``s that follow the actor defined by ``content_type_id``, ``object_id``. """ if request.user.is_authenticated(): ctype = get_object_or_404(ContentType, pk=content_type_id) actor = get_object_or_404(ctype.model_class(), pk=object_id) return render_to_response('social/followers.html', { 'followers': models.followers(actor), 'actor': actor }, context_instance=RequestContext(request)) else: return redirect("/accounts/login/?next=/")
def following(request, user_id): """ Returns a list of actors that the user identified by ``user_id`` is following (eg who im following). """ if request.user.is_authenticated(): user = get_object_or_404(User, pk=user_id) return render_to_response('social/following.html', { 'following': models.following(user), 'followers': models.followers(user), 'user': user }, context_instance=RequestContext(request)) else: return redirect("/accounts/login/?next=/")
def user_followers_delete_handler(sender, instance, **kwargs): """ Make all users unfollow the user being deleted. N.B. Because django-activity-stream is using a GFK, these do not cascade delete. """ # Import act_models here. If imported at the top, this interferes with # appconf imports and breaks compressor configuration. # See https://github.com/jezdez/django_compressor/issues/333 from actstream import models as act_models followers = act_models.followers(instance) for follower in followers: unfollow(follower, instance)
def user(request, username, active_tab='activity'): user_to_show = get_object_or_404(User, username=username) # If edit tab is requested, check whether user should have access if (active_tab == 'edit') and (request.user.id != user.id): return redirect('users:user', username = username) context = { 'active_page': '', 'active_tab': active_tab, 'user_to_show': user_to_show, 'following': following(user_to_show), 'followers': followers(user_to_show), } return render(request, "user.html", context)
def activity_count(obj): """ Increments the activity stream counter of the followers of the given object to make a Facebook look and feel on the top bar. """ from actstream.models import followers if not obj: return 0 for user in followers(obj): name = 'user_%d_activity_counter' % user.id count = get_option(name) try: count = int(count) except: count = 0 update_option(name, count+1)
def profile_related_list(request, username, relation): "Render the list of a users folllowers or who the user is following" profile = get_object_or_404(Profile, user__username__iexact=username) if profile.user.username != username: return redirect(profile, permanent=True) user = profile.user # get a queryset of users described by this relationship if relation == 'followers': related_users = models.followers(user) elif relation == 'following': related_users = models.following(user) return render(request, "accounts/account_profile_related.html", { 'user': user, 'profile': profile, 'related_users': related_users, })
def profile(request, username=None): """ User profile page. """ user = User.objects.get(username__exact=username) profile = user.get_profile() form = CellarItemForm() follow_state = request.user.is_authenticated() and user in following(request.user) context = { 'this_user': user, 'username': user.username, 'email': user.email, 'cellar': list(profile.cellar.all()), 'wants': list(profile.wants.all()), 'form': form, 'activity': actor_stream(user), 'friends_activity': user_stream(user), 'following': following(user), 'followers': followers(user), 'follow_state': follow_state, } return render(request, 'users/profile.html', context)
def followers(self): return followers(self.user)
def test_followers(self): self.assertEqual(list(followers(self.group)), [self.user2])