コード例 #1
0
ファイル: views.py プロジェクト: NavaneethBhat/SongSanthe
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)
コード例 #2
0
ファイル: models.py プロジェクト: uppm66/uppm
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
コード例 #3
0
 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])
コード例 #4
0
 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))
コード例 #5
0
 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, })
コード例 #6
0
ファイル: api.py プロジェクト: gitter-badger/CivilHub
 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, })
コード例 #7
0
    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))
コード例 #8
0
ファイル: views.py プロジェクト: cmwaura/social-site
    def get_user_followee(self):
        '''
		people that the self.request.user is following
		'''

        followee = following(self.request.user)
        return followee
コード例 #9
0
    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,
        })
コード例 #10
0
    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)),
        )
コード例 #11
0
ファイル: views.py プロジェクト: JigsawYang/raspberryio
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,
    })
コード例 #12
0
ファイル: views.py プロジェクト: max-weller/pydocman
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
    })
コード例 #13
0
ファイル: actstream_tags.py プロジェクト: tapiau/CivilHub
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)
コード例 #14
0
ファイル: views.py プロジェクト: widley215/HallWay
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
コード例 #15
0
ファイル: actstream_tags.py プロジェクト: cristianlp/CivilHub
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)
コード例 #16
0
ファイル: views.py プロジェクト: digimatronics/raspberry
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,
    })
コード例 #17
0
ファイル: views.py プロジェクト: NavaneethBhat/SongSanthe
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)
コード例 #18
0
ファイル: serializers.py プロジェクト: tapiau/CivilHub
 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)
コード例 #19
0
ファイル: views.py プロジェクト: Doublexe/GalaX
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)
コード例 #20
0
ファイル: views.py プロジェクト: andyxmai/pickup
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)
		})
コード例 #21
0
    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')
コード例 #22
0
ファイル: views.py プロジェクト: widley215/HallWay
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)
			})
コード例 #23
0
ファイル: views.py プロジェクト: piotrek-golda/CivilHubCopy
    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, })
コード例 #24
0
ファイル: fakestream.py プロジェクト: mpuig/gustosity
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)
コード例 #25
0
ファイル: views.py プロジェクト: andyxmai/pickup
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
		})
コード例 #26
0
ファイル: views.py プロジェクト: sdob/dsapi
 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)
コード例 #27
0
ファイル: views.py プロジェクト: Ramenetagraine/permacat
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')
コード例 #28
0
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))
コード例 #29
0
    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
コード例 #30
0
ファイル: list.py プロジェクト: b-meson/muckrock
 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)
コード例 #31
0
ファイル: views.py プロジェクト: Anabella1109/MyGram
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})
コード例 #32
0
ファイル: views.py プロジェクト: eloigrau/Pacte
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')
コード例 #33
0
    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)})
コード例 #34
0
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))
コード例 #35
0
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
    })
コード例 #36
0
ファイル: tests.py プロジェクト: avances123/huertos-api
    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)
コード例 #37
0
ファイル: models.py プロジェクト: mpuig/gustosity
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()
コード例 #38
0
ファイル: models.py プロジェクト: mpuig/gustosity
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()
コード例 #39
0
 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
コード例 #40
0
ファイル: views.py プロジェクト: oskarm91/CivilHub
 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
コード例 #41
0
ファイル: views.py プロジェクト: shvms/Mozart-backend
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)
コード例 #42
0
ファイル: views.py プロジェクト: Anabella1109/MyGram
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})
コード例 #43
0
ファイル: views.py プロジェクト: tony/django-activity-stream
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
    })
コード例 #44
0
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)
コード例 #45
0
ファイル: views.py プロジェクト: Ramenetagraine/permacat
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)
コード例 #46
0
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)
コード例 #47
0
ファイル: views.py プロジェクト: sdob/dsapi
    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)
コード例 #48
0
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')
コード例 #49
0
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 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),
    )
コード例 #51
0
ファイル: views.py プロジェクト: BeerCoin/beercoin-service
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
コード例 #52
0
ファイル: views.py プロジェクト: d-a-l/redpanal
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=/")
コード例 #53
0
ファイル: api.py プロジェクト: cristianlp/CivilHub
 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, })
コード例 #54
0
    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))
コード例 #55
0
ファイル: views.py プロジェクト: mpuig/gustosity
    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)
コード例 #56
0
ファイル: coordinator.py プロジェクト: kevinlee12/iU
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})