def get_following_list(request,user_pk): """List of users followed by user_pk""" connection = User.objects.get(pk=user_pk) node = request.user connection_follows = following(User.objects.get(pk=user_pk)) node_follows = following(node) following_list = [] for connected in connection_follows: if connected in node_follows: following_list.append({"followed_by_connection":connected, "followed_by_me":"Following"}) else: following_list.append({"followed_by_connection":connected, "followed_by_me":"Not Following"}) is_cur_user = False if (request.user == connection): is_cur_user = True ctx = { "following_list": following_list, "is_cur_user" : is_cur_user, "connection" : connection.first_name, "cur_user" : connection, } print 'following' print following_list return render(request,"profile/user_connections.html",ctx)
def getOrCreateConversation(nom1, nom2): try: convers = Conversation.objects.get( slug=get_slug_from_names(nom1, nom2)) except Conversation.DoesNotExist: profil_1 = Profil.objects.get(username=nom1) profil_2 = Profil.objects.get(username=nom2) convers = Conversation.objects.create(profil1=profil_1, profil2=profil_2) conversations = Conversation.objects.filter( Q(profil2=profil_1) | Q(profil1=profil_1)) for conv in conversations: if conv in following(profil_1): actions.follow(profil_1, convers) break conversations = Conversation.objects.filter( Q(profil2=profil_2) | Q(profil1=profil_2)) for conv in conversations: if conv in following(profil_2): actions.follow(profil_2, convers) break return convers
def test_following_with_flag(self): self.assertCountEqual(list(following(self.user4, flag='liking')), [self.another_group, self.user1]) self.assertEqual(list(following(self.user4, flag='watching')), [self.another_group]) self.assertEqual(list(following(self.user4, flag='blacklisting')), [self.user3]) self.assertEqual(list(following(self.user4, self.User, flag='liking')), [self.user1])
def test_follow_project(self): unfollow_project(self.user, self.project) self.assertNotIn(self.project, following(self.user)) # follow the project with the follow button self.client.get( reverse('project:detail', kwargs={'project': project_settings['name_short']}) + "?follow=true") self.assertIn(self.project, following(self.user))
def post(self, request, **kwargs): user = request.user self.location = self._get_location() if self.location in following(user): unfollow(user, self.location) self.location.users.remove(user) msg = _(u"You stopped following") else: follow(user, self.location, actor_only=False, send_action=False) self.location.users.add(user) msg = _(u"You are following") return Response( {'following': self.location in following(user), 'message': msg, })
def test_unfollow_project(self): # unfollow the project with the unfollow button on the dashboard self.client.get( reverse('landing_page:home') + "?unfollow=" + str(self.project.pk)) self.assertNotIn(self.project, following(self.user)) # follow the project again follow_project(self.user, self.project) # unfollow the project with the unfollow button on the project page self.client.get( reverse('project:detail', kwargs={'project': project_settings['name_short']}) + "?follow=false") self.assertNotIn(self.project, following(self.user))
def get_user_followee(self): ''' people that the self.request.user is following ''' followee = following(self.request.user) return followee
def post(self, request): self.instance = self.get_object() instance_name = self.instance._meta.model_name if not self.instance in following(request.user): try: follow(request.user, self.instance, actor_only=False, send_action=False) msg = _(u"You are following this %s" % instance_name) is_follower = True except ImproperlyConfigured as e: return Response({'success': False, 'message': str(e)}) if instance_name == 'location': self.instance.users.add(request.user) elif instance_name == 'user': new_follower(request.user, self.instance) else: unfollow(request.user, self.instance) msg = _(u"You are no longer following this %s" % instance_name) is_follower = False if instance_name == 'location': self.instance.users.remove(request.user) return Response({ 'success': True, 'message': msg, 'following': is_follower, })
def test_create_step3_executed(self): # DO ACTION self.consultant = Consultant.objects.create_consultant( short_name=faker.first_name(), email=faker.email(), invite_user=self.super_user, registration_process=True, version=3, ) process = self.consultant.registration_process step = process.steps.first() invitation = step.invitation invitation.accept(invitation.user) current_step = process.current_step invitation = current_step.invitation invitation.accept(self.consultant.user) invitation = process.current_step.invitation invitation.accept(invitation.user) consultant_default_circles = Circle.objects.filter( name__in=settings.CIRCLES_FOR_CONSULTANTS) # ASSERTS self.assertTrue(process.is_registered) self.consultant.refresh_from_db() self.assertTrue(self.consultant.is_active) self.assertEqual( set(list(following(self.consultant.user, Circle))), set(list(consultant_default_circles)), )
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 dashboard(request): events = user_stream(request.user, with_user_activity=True) cbs = following(request.user, Clipboard) return render(request, "dropme/dashboard.html", { "events": events, "following_clipboards": cbs })
def follow_button(context, obj): """ Displays follow button for any target object. It is supposed to work with some kind of front-end scripts. """ user = context['user'] class_name = 'btn-follow' label_text = _(u"Follow") if user.is_anonymous(): href = '/user/login/?next=' + context['request'].path return '<a class="{}" href="{}">{}</a>'.format(class_name, href, label_text) elif user == obj: return '' if obj in following(user): class_name = 'btn-unfollow' label_text = _(u"Stop following") content_type = ContentType.objects.get_for_model(obj).pk template = """<a class="civ-follow-btn {}" href="#" data-ct="{}" data-pk="{}">{}</a>""" return template.format(class_name, content_type, obj.pk, label_text)
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 follow_button(context, obj): """ Displays follow button for any target object. It is supposed to work with some kind of front-end scripts. """ user = context['user'] class_name = 'btn-follow' label_text = _(u"Follow") if user.is_anonymous(): href = '/user/login/?next=' + context['request'].path return '<a class="{}" href="{}">{}</a>'.format( class_name, href, label_text) elif user == obj: return '' if obj in following(user): class_name = 'btn-unfollow' label_text = _(u"Stop following") content_type = ContentType.objects.get_for_model(obj).pk template = """<a class="civ-follow-btn {}" href="#" data-ct="{}" data-pk="{}">{}</a>""" return template.format(class_name, content_type, obj.pk, label_text)
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 check_followed(self, obj): request = self.context.get('request') if request is None: return False if request.user.is_anonymous(): return False return obj in following(request.user)
def category(request): response = {} is_login = request.session.get('is_login', None) if request.is_ajax() and is_login: if request.method == 'POST': data = json.loads(request.body) option = data.get('option') response['status'] = 0 else: response['status'] = 1 response = json.dumps(response) return HttpResponse(response) user_id = request.session.get('user_id', None) # depend on option, find corresponding events if option == "自己": events = Event.objects.filter(owner__id=user_id) elif option == "朋友": friends = following(User.objects.get(pk=user_id)) events = [] for friend in friends: events.append(Event.objects.filter(owner__id=friend.id)) # elif option == "热点": else: raise ValueError("Option is invalid: " + option) # Format events. Send JSON. # If empty events, return an empty json array. response = [format_event(event, user_id) for event in events] response = json.dumps(response) return HttpResponse(response)
def profile(request): loggedinUser = request.user user = request.user games_created = Game.objects.filter(creator=user) games_played = Game.objects.filter(timeStart__lt=datetime.datetime.now()).order_by('-timeStart'); upcoming_games = user.game_set.all().filter(timeStart__gte=datetime.datetime.now()).order_by('timeStart'); connected_to_instagram = False if InstagramInfo.objects.filter(user=user).count(): connected_to_instagram = True print FACEBOOK_URL return render(request, 'user.html', {'player':user, 'games_played':games_played, 'games_created':games_created, 'upcoming_games': upcoming_games, 'loggedinUser':loggedinUser, 'instagramID' : INSTAGRAM_ID, 'instagramSecret' : INSTAGRAM_SECRET, 'redirectURL' : REDIRECT_URL, 'connected_to_instagram': connected_to_instagram, 'facebookID' : FACEBOOK_APP_ID, 'websiteURL' : FACEBOOK_URL, 'following' : following(request.user) })
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 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 post(self, request): self.instance = self.get_object() instance_name = self.instance._meta.verbose_name.lower() if not self.instance in following(request.user): try: follow(request.user, self.instance, actor_only=False, send_action=False) msg = _(u"You are following this %s" % instance_name) is_follower = True except ImproperlyConfigured as e: return Response({'success': False, 'message': str(e)}) if instance_name == 'location': self.instance.users.add(request.user) else: unfollow(request.user, self.instance) msg = _(u"You are no longer following this %s" % instance_name) is_follower = False if instance_name == 'location': self.instance.users.remove(request.user) return Response( {'success': True, 'message': msg, 'following': is_follower, })
def make_random_unfollows(max_users): print "make random unfollows" some_users = User.objects.all().order_by('?')[:random.randint(0, max_users)] for user in some_users: following_list = following(user, User) for u in following_list[:random.randint(0, len(following_list))]: unfollow(user, u)
def user(request, id): loggedinUser = request.user player = User.objects.get(pk=id) if player == loggedinUser: return redirect('/profile') print user_stream(request.user) games_created = Game.objects.filter(creator=player) games_played = player.game_set.all().filter(timeStart__lt=datetime.datetime.now()).order_by('-timeStart'); upcoming_games = player.game_set.all().filter(timeStart__gte=datetime.datetime.now()).order_by('timeStart'); player_connected_to_instagram = False if InstagramInfo.objects.filter(user=player).count(): player_connected_to_instagram = True following_people = following(request.user) is_following = player in following_people return render(request, 'user.html', { 'player':player, 'games_played':games_played, 'games_created':games_created, 'upcoming_games': upcoming_games, 'loggedinUser':loggedinUser, 'player_connected_to_instagram': player_connected_to_instagram, 'is_following' : is_following })
def follows(self, request, pk): queryset = Profile.objects.all() profile = get_object_or_404(queryset, pk=pk) user = profile.user targets = following(user) profiles = [_.profile for _ in targets] serializer = MinimalProfileSerializer(profiles, many=True) return Response(serializer.data)
def suivre_produits(request, actor_only=True): suivi, created = Suivis.objects.get_or_create(nom_suivi = 'produits') if suivi in following(request.user): actions.unfollow(request.user, suivi) else: actions.follow(request.user, suivi, actor_only=actor_only) return redirect('marche')
def following(request, user_id): """ Returns a list of actors that the user identified by ``user_id`` is following (eg who im following). """ user = get_object_or_404(User, pk=user_id) return render_to_response(('actstream/following.html', 'activity/following.html'), { 'following': models.following(user), 'user': user }, context_instance=RequestContext(request))
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 get_queryset(self): """Limits FOIAs to those followed by the current user""" queryset = super(FollowingRequestList, self).get_queryset() followed = [ f.pk for f in following(self.request.user, FOIARequest) if f is not None ] return queryset.filter(pk__in=followed)
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 suivre_suffrages(request, actor_only=True): suivi, created = Suivis.objects.get_or_create(nom_suivi='suffrages') if suivi in following(request.user): actions.unfollow(request.user, suivi) else: actions.follow(request.user, suivi, actor_only=actor_only) return redirect('vote:index')
def post(self, request): target_user = None pk = request.DATA.get('pk', None) try: target_user = User.objects.get(pk=pk) except User.DoesNotExist: pass if target_user is None: raise Http404() if target_user in following(request.user): unfollow(request.user, target_user) else: follow(request.user, target_user, actor_only=True) return Response({'follow': target_user in following(request.user)})
def following(request, user_id): """ Returns a list of actors that the user identified by ``user_id`` is following (eg who im following). """ instance = get_object_or_404(User, pk=user_id) return render(request, 'actstream/following.html', context={ 'following': models.following(instance), 'user': instance })
def test_follow_a_farm(self): other_user = User.objects.create_user(username=fake.user_name(),password=fake.password(),email=fake.email()) other_farm = Farm.objects.create(owner=other_user) url = reverse('farm-follow',kwargs={'pk': other_farm.id}) self.client.post(url,{},format='json') siguiendo = following(self.user) self.assertEqual(len(siguiendo),1) self.assertEqual(siguiendo[0],other_farm)
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 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 get_context_data(self, **kwargs): context = super(UserActivityView, self).get_context_data(**kwargs) if len(following(self.request.user)) > 0: actstream = user_stream(self.request.user) context['blog'] = self.get_latest(actstream, 'blog') context['ideas'] = self.get_latest(actstream, 'ideas') context['topics'] = self.get_latest(actstream, 'topics') context['polls'] = self.get_latest(actstream, 'polls') return context
def following_view(request): """ View to show a list of users the current user is following. """ f = following(request.user) serializer = UserShortSerializer(instance=f, context={'request': request}, many=True) return Response(serializer.data)
def home(request): title='Home | MyGram' current_user=request.user profile=Profile.objects.get(user=current_user) following1=following(request.user) posts=Image.objects.all() return render(request,'grams/home.html',{'title':title , 'posts':posts, 'following':following1})
def following(request, user_id): """ Returns a list of actors that the user identified by ``user_id`` is following (eg who im following). """ instance = get_object_or_404(User, pk=user_id) return render(request, 'actstream/following.html', { 'following': models.following(instance), 'user': instance })
def suivre_article(request, slug, actor_only=True): """ """ article = get_object_or_404(Article, slug=slug) if article in following(request.user): actions.unfollow(request.user, article) else: actions.follow(request.user, article, actor_only=actor_only) return redirect(article)
def suivre_projet(request, slug, actor_only=True): """ """ projet = get_object_or_404(Projet, slug=slug) if projet in following(request.user): actions.unfollow(request.user, projet) else: actions.follow(request.user, projet, actor_only=actor_only) return redirect(projet)
def follow_button(context, obj): user = context['user'] if user.is_anonymous(): return '' if obj in following(user): txt = _(u"Stop following") else: txt = _(u"Follow") return '<a class="civ-follow-btn" href="#" data-ct="{}" data-pk="{}">{}</a>'.format( ContentType.objects.get_for_model(obj).pk, obj.pk, txt)
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 suivre_conversations(request, actor_only=True): """ """ conversations = Conversation.objects.filter(Q(profil2__id=request.user.id) | Q(profil1__id=request.user.id)) for conv in conversations: if conv in following(request.user): actions.unfollow(request.user, conv) else: actions.follow(request.user, conv, actor_only=actor_only) return redirect('conversations')
def following(request, user_id): """ Returns a list of actors that the user identified by ``user_id`` is following (eg who im following). """ instance = get_object_or_404(User, pk=user_id) return render_to_response( "actstream/following.html", {"following": models.following(instance), "user": instance}, context_instance=RequestContext(request), )
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 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), 'user': user }, context_instance=RequestContext(request)) else: return redirect("/accounts/login/?next=/")
def post(self, request, **kwargs): id_list = [int(x.strip()) for x in request.POST.get('id').split(',')] for user in User.objects.filter(id__in=id_list): if not user in following(request.user): follow(request.user, user, send_action=False) new_follower(request.user, user) message = _(u"You have started following your friends!") return Response({ 'success': True, 'label': _(u"Stop following"), 'message': message, })
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 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 coordinator(request): coor = Coordinator.objects.get(user=request.user) students = coor.students.all().order_by('last_name') advisors = coor.advisors.all().order_by('first_name') if not following(request.user): for student in students: follow(request.user, student) follow(User.objects.get(email=student.user.email), coor) return render(request, 'journal/coordinator.html', {'feed': user_stream(request.user), 'students': students, 'coordinator': coor, 'advisors': advisors})