コード例 #1
0
ファイル: views.py プロジェクト: trb116/pythonanalyzer
    def get_context_data(self, **kwargs):
        context = super(FriendsPageView, self).get_context_data(**kwargs)
        # TODO use a query parameter for the time delta. here is 3 months
        ago = datetime.datetime.now() - datetime.timedelta(30)
        friends = friend_set_for(self.request.user)

        tweets = [
            TimeLineItem(item, item.sent, item.sender, "timeline/_tweet.html")
            for item in Tweet.objects.all().filter(
                sent__gte=ago,
                sender_id__in=[user.id for user in friends],
                sender_type__model="user").order_by("-sent")
        ]

        posts = [
            TimeLineItem(item, item.publish, item.author,
                         "timeline/_post.html")
            for item in Post.objects.all().filter(
                publish__gte=ago, status=2, author__in=friends).order_by(
                    "-publish")
        ]

        images = [
            TimeLineItem(item, item.date_added, item.member,
                         "timeline/_photo.html")
            for item in Image.objects.all().filter(
                Q(is_public=True)
                | Q(member__in=friend_set_for(self.request.user))).filter(
                    date_added__gte=ago, member__in=friends).order_by(
                        "-date_added")
        ]

        tracks = [
            TimeLineItem(item, item.updated_at, item.user,
                         "timeline/_track.html")
            for item in Track.objects.all().filter(
                created_at__gte=ago, user__in=friends).order_by("-created_at")
        ]

        comments = [
            TimeLineItem(item, item.date_submitted, item.user,
                         "timeline/_comment.html")
            for item in ThreadedComment.objects.all().filter(
                date_submitted__gte=ago, user__in=friends).order_by(
                    "-date_submitted")
        ]

        items = merge(tweets, images, posts, tracks, comments, field="date")
        for index, item in enumerate(items):
            item.index = index + 1

        context['timelineitems'] = group_comments(items)
        context['prefix_sender'] = True
        return context
コード例 #2
0
def friends_objects(request,
                    template_name,
                    friends_objects_function,
                    extra_context={}):
    """
    Display friends' objects.
    
    This view takes a template name and a function. The function should
    take an iterator over users and return an iterator over objects
    belonging to those users. This iterator over objects is then passed
    to the template of the given name as ``object_list``.
    
    The template is also passed variable defined in ``extra_context``
    which should be a dictionary of variable names to functions taking a
    request object and returning the value for that variable.
    """

    friends = friend_set_for(request.user)

    dictionary = {
        "object_list": friends_objects_function(friends),
    }
    for name, func in extra_context.items():
        dictionary[name] = func(request)

    return render_to_response(template_name,
                              dictionary,
                              context_instance=RequestContext(request))
コード例 #3
0
ファイル: views.py プロジェクト: amarandon/smeuhsocial
def most_viewed(request, template_name="photos/latest.html"):
    """
    latest photos
    """
    
    group, bridge = group_and_bridge(request)
    
    photos = Image.objects.filter(
        Q(is_public=True) | Q(member=request.user) 
        | Q(member__in=friend_set_for(request.user))
    )
    
    if group:
        photos = group.content_objects(photos, join="pool", gfk_field="content_object")
    else:
        photos = photos.filter(pool__object_id=None)
    
    photos = photos.order_by("-view_count")
    
    ctx = group_context(group, bridge)
    ctx.update({
        "photos": photos,
        "title": _("Most Viewed Photos")
    })
    
    return render(request, template_name, ctx)
コード例 #4
0
def details(request, id, template_name="photos/details.html"):
    """
    show the photo details
    """
    photos = Image.objects.all()
    photos = photos.filter(pool__object_id=None)

    image_filter = Q(is_public=True)

    if request.user.is_authenticated():
        # allow owner and friend to see a private photo
        image_filter = image_filter | Q(member=request.user) | Q(
            member__in=friend_set_for(request.user))

    try:
        photo = photos.filter(image_filter, id=id)[0]
    except IndexError:
        raise Http404

    previous_photo_id = get_first_id_or_none(
        photos.filter(image_filter, id__lt=photo.id).order_by('-id'))

    next_photo_id = get_first_id_or_none(
        photos.filter(image_filter, id__gt=photo.id).order_by('id'))

    ctx = {
        "photo": photo,
        "photo_url": request.build_absolute_uri(photo.get_display_url()),
        "url": request.build_absolute_uri(),
        "is_me": photo.member == request.user,
        "previous_photo_id": previous_photo_id,
        "next_photo_id": next_photo_id,
    }

    return render_to_response(template_name, RequestContext(request, ctx))
コード例 #5
0
ファイル: views.py プロジェクト: cjs/bme
def friends(request, username):
    user = get_object_or_404( User, username=username)
    friends = friend_set_for(user)

    checkins = CheckIn.objects.filter(owner__in=friends)

    paginator = Paginator(checkins, 25)

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        page = paginator.page(page)
    except (EmptyPage, InvalidPage):
        page = paginator.page(paginator.num_pages)


    return object_list( request,
            queryset = checkins,
            paginate_by=25,
            extra_context=locals(),
    )
コード例 #6
0
ファイル: views.py プロジェクト: amarandon/smeuhsocial
    def get_context_data(self, **kwargs):
        context = super(UserPageView, self).get_context_data(**kwargs)
        name = context.get('username', None)
        limit = 64
        if name:
            user = other_user = get_object_or_404(User, username=name)
        else:
            user = other_user = self.request.user
        
        if self.request.user == other_user:
            context['is_me'] = True
            context['is_friend'] = False
        elif self.request.user.is_authenticated():
            context['is_friend'] = Friendship.objects.are_friends(self.request.user, other_user)
            context['is_following'] = Following.objects.is_following(self.request.user, other_user)
        context['other_friends'] = Friendship.objects.friends_for_user(other_user)
        context['other_user'] = other_user
        
        tweets = [
            TimeLineItem(item, item.sent, item.sender, "timeline/_tweet.html")
            for item in Tweet.objects.all().filter(sender_id=user.id, sender_type__model="user").order_by("-sent")[:limit]
            ]

        context['latest_blogs'] = Post.objects.all().filter(status=2, author=user).order_by("-publish")[:limit]

        posts = [
            TimeLineItem(item, item.updated_at, item.author, "timeline/_post.html")
            for item in context['latest_blogs']
            ]

        image_filter = Q(is_public=True, member=user)

        if self.request.user.is_authenticated():
            image_filter = image_filter | Q(member=user, member__in=friend_set_for(self.request.user))

        context['latest_photos'] = Image.objects.all().filter(image_filter).order_by("-date_added")[:limit]

        images = [
            TimeLineItem(item, item.date_added, item.member, "timeline/_photo.html")
            for item in context['latest_photos']
            ]

        context['latest_tracks'] = Track.objects.all().filter(user=user).order_by("-created_at")[:limit]

        tracks = [
            TimeLineItem(item, item.updated_at, item.user, "timeline/_track.html")
            for item in context['latest_tracks']
            ]

        comments = [
            TimeLineItem(item, item.date_submitted, item.user, "timeline/_comment.html")
            for item in ThreadedComment.objects.all().filter(user=user).order_by("-date_submitted")[:limit]
            ]
        
        items = merge(tweets, images, posts, tracks, comments, field="date")
        for index, item in enumerate(items):
            item.index = index + 1
        context['timelineitems'] = group_comments(items)[:limit]
        context['prefix_sender'] = True        
        return context
コード例 #7
0
ファイル: views.py プロジェクト: fo0nikens/smeuhsocial
def photos(request, template_name="photos/latest.html"):
    """
    latest photos
    """
    
    group, bridge = group_and_bridge(request)
    
    photos = Image.objects.filter(
        Q(is_public=True) | Q(member=request.user)  | 
        Q(member__in=friend_set_for(request.user))
    )
    
    if group:
        photos = group.content_objects(photos, join="pool", gfk_field="content_object")
    else:
        photos = photos.filter(pool__object_id=None)
    
    photos = photos.order_by("-date_added")
    
    ctx = group_context(group, bridge)
    ctx.update({
        "photos": photos,
        "title": "Latest Photos"
    })
    
    return render_to_response(template_name, RequestContext(request, ctx))
コード例 #8
0
ファイル: views.py プロジェクト: SuLab/biogps_core
def view(request, userid, junk=''):
    try:
        vuser = User.objects.get(id=userid)
    except:
        raise Http404

    # Confirm that the userid and username in the URL match
    if not clean_username(vuser.username).lower() == junk.lower().replace('.html', ''):
        raise Http404

    d = getCommonDataForMain(request)
    d['vuser'] = vuser

    # get_or_create returns a tuple with the object we want as the first item.
    profile_tuple = BiogpsProfile.objects.get_or_create(user=vuser)
    d['vprofile'] = profile_tuple[0].filter_for_user(request.user)

    d['vplugins'] = BiogpsPlugin.objects.get_available_from(vuser, request.user)

    if not request.user.is_anonymous():
        d['isOwner'] = d['vprofile'].belongs_to(request.user)
        d['isFriend'] = vuser.is_friends_with(request.user)
        if not d['isFriend']:
            d['inviteStatus'] = vuser.invite_status_with(request.user)
            d['inverseInviteStatus'] = request.user.invite_status_with(vuser)

    d['vfriends'] = friend_set_for(vuser)

    if settings.DEBUG:
        from django.template.context_processors import request as request_processor
        context = RequestContext(request, {}, (request_processor,))
    else:
        context = RequestContext(request)
    return render_to_response('profile/view.html', d, context_instance=context)
コード例 #9
0
def sync_chatbox(request, target):
    """
    Depending on the target argument value, the view either returns
    new chat requests for the logged in user or a list of online users,
    provided by the useractivity app.
    """
    if target == "chat_requests":
        now = datetime.now()

        # Checking for the timestamp in session data, explanations
        # are below.
        timestamp = request.session.get("im:chat_requests:sync", now)
        chat_requests = ChatRequest.objects.incoming(request.user, timestamp)
        data = map(
            lambda chat_request: render_to(request, "im/chat_request.html", {"chat_request": chat_request}),
            chat_requests,
        )

        # Saving last check timestamp in session data, so we can later
        # determine which requests were already sent to the browser.
        request.session["im:chat_requests:sync"] = now
    elif target == "online_users":
        friends = friend_set_for(request.user)
        online_users = get_online_users()
        if request.user in online_users:
            online_users.remove(request.user)
        online_friends = online_users & friends
        online_others = online_users - friends

        data = render_to(request, "im/userlist.html", {"friends": online_friends, "others": online_others})

    return json_response(data)
コード例 #10
0
def friends(request, username):
    user = get_object_or_404(User, username=username)
    friends = friend_set_for(user)

    checkins = CheckIn.objects.filter(owner__in=friends)

    paginator = Paginator(checkins, 25)

    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        page = paginator.page(page)
    except (EmptyPage, InvalidPage):
        page = paginator.page(paginator.num_pages)

    return object_list(
        request,
        queryset=checkins,
        paginate_by=25,
        extra_context=locals(),
    )
コード例 #11
0
ファイル: views.py プロジェクト: amarandon/smeuhsocial
def user_photos(request, username, template_name="photos/user_photos.html"):
    """
    Get the photos of a user and display them
    """
        
    user = get_object_or_404(User, username=username)
    
    image_filter = Q(is_public=True)

    if request.user.is_authenticated():
        image_filter = image_filter | Q(member=request.user) | Q(member__in=friend_set_for(request.user))
    
    photos = Image.objects.filter(
        image_filter,
        member=user
        
    )           
    photos = photos.order_by("-date_added")
    group, bridge = group_and_bridge(request)
    ctx = group_context(group, bridge)
    ctx.update({
        "photos": photos,
        "username": username
    })    
    return render(request, template_name, ctx)
コード例 #12
0
ファイル: views.py プロジェクト: amarandon/smeuhsocial
def random(request):
    image_filter = Q(is_public=True)

    if request.user.is_authenticated():
        image_filter = image_filter | Q(member=request.user) | Q(member__in=friend_set_for(request.user))
        
    photo = Image.objects.filter(image_filter).order_by('?')[0]    
    return HttpResponseRedirect(reverse('photo_details', args=(photo.id,)))
コード例 #13
0
def random(request):
    image_filter = Q(is_public=True)

    if request.user.is_authenticated():
        image_filter = image_filter | Q(member=request.user) | Q(
            member__in=friend_set_for(request.user))

    photo = Image.objects.filter(image_filter).order_by('?')[0]
    return HttpResponseRedirect(reverse('photo_details', args=(photo.id, )))
コード例 #14
0
ファイル: views.py プロジェクト: amarandon/smeuhsocial
    def get_context_data(self, **kwargs):
        context = super(TagPageView, self).get_context_data(**kwargs)
        tag_instance = get_object_or_404(Tag, name__iexact=context.get("tagname"))                       
        
        context['tag'] = tag = tag_instance.name
        
        # ago = datetime.datetime.now() - datetime.timedelta(30)
        
        # limit = 64
        
        tweets = [
            TimeLineItem(item, item.sent, item.sender, "timeline/_tweet.html")
            for item in TaggedItem.objects.get_by_model(Tweet, tag).order_by("-sent")  # [:limit]
            ]

        context['latest_blogs'] = TaggedItem.objects.get_by_model(Post, tag).filter(status=2).order_by("-publish")  # [:limit]

        posts = [
            TimeLineItem(item, item.updated_at, item.author, "timeline/_post.html")
            for item in context['latest_blogs']
            ]

        image_filter = Q(is_public=True)

        if self.request.user.is_authenticated():
            image_filter = image_filter | Q(member=self.request.user) | Q(member__in=friend_set_for(self.request.user))

        context['latest_photos'] = TaggedItem.objects.get_by_model(Image, tag).filter(image_filter).order_by("-date_added")  # [:limit]

        images = [
            TimeLineItem(item, item.date_added, item.member, "timeline/_photo.html")
            for item in context['latest_photos']
            ]

        context['latest_tracks'] = TaggedItem.objects.get_by_model(Track, tag).order_by("-created_at")        

        tracks = [
            TimeLineItem(item, item.created_at, item.user, "timeline/_track.html")
            for item in context['latest_tracks']
            ]

        comments = [
            TimeLineItem(item, item.date_submitted, item.user, "timeline/_comment.html")
            for item in TaggedItem.objects.get_by_model(ThreadedComment, tag).order_by("-date_submitted")
            ]
        
        # no tag for comment yet. so : no comment :)
        
        # Tag.objects.get_for_object(self.obj.resolve(context))
        
        
        items = merge(tweets, images, posts, tracks, comments, field="date")
        for index, item in enumerate(items):
            item.index = index + 1
        context['timelineitems'] = group_comments(items) 
        context['prefix_sender'] = True
        return context
コード例 #15
0
ファイル: models.py プロジェクト: SuLab/biogps_core
 def get_available_by_friendship(self, user):
     object_type = self.model.object_type
     shared_objects_byfriendship = self.none()
     if user:
         #Check if the object is shared with me by my friends
         myfriends = [f.username for f in friend_set_for(user)]
         perm_qs = BiogpsPermission.objects.filter(object_type=object_type,
                                                   permission_type='F',
                                                   permission_value__in=myfriends)
         shared_objects_byfriendship = self.filter(pk__in=perm_qs.values('object_id'))
     return shared_objects_byfriendship
コード例 #16
0
ファイル: views.py プロジェクト: amarandon/smeuhsocial
    def get_context_data(self, **kwargs):
        context = super(HomePageView, self).get_context_data(**kwargs)
        # reduce the timeline items
        context['timelineitems'] = group_comments(context['timelineitems'][:16])
        image_filter = Q(is_public=True)

        if self.request.user.is_authenticated():
            image_filter = image_filter | Q(member=self.request.user) | Q(member__in=friend_set_for(self.request.user))
        context['latest_photos'] = Image.objects.all().filter(image_filter).order_by("-date_added")[:16]
        context['latest_blogs'] = Post.objects.all().filter(status=2).order_by("-publish")[:10]
        context['latest_tracks'] = Track.objects.all().order_by("-created_at")[:6]
        return context
コード例 #17
0
ファイル: views.py プロジェクト: amarandon/smeuhsocial
    def get_context_data(self, **kwargs):
        context = super(FriendsPageView, self).get_context_data(**kwargs)
        # TODO use a query parameter for the time delta. here is 3 months
        ago = datetime.datetime.now() - datetime.timedelta(30)
        friends = friend_set_for(self.request.user)

        tweets = [
            TimeLineItem(item, item.sent, item.sender, "timeline/_tweet.html")
            for item in Tweet.objects.all().filter(sent__gte=ago, sender_id__in=[user.id for user in friends], sender_type__model="user").order_by("-sent")
            ]

        posts = [
            TimeLineItem(item, item.publish, item.author, "timeline/_post.html")
            for item in Post.objects.all().filter(publish__gte=ago, status=2, author__in=friends).order_by("-publish")
            ]

        images = [
            TimeLineItem(item, item.date_added, item.member, "timeline/_photo.html")
            for item in Image.objects.all().filter(Q(is_public=True) | Q(member__in=friend_set_for(self.request.user))).filter(date_added__gte=ago, member__in=friends).order_by("-date_added")
            ]

        tracks = [
            TimeLineItem(item, item.updated_at, item.user, "timeline/_track.html")
            for item in Track.objects.all().filter(created_at__gte=ago, user__in=friends).order_by("-created_at")
            ]

        comments = [
            TimeLineItem(item, item.date_submitted, item.user, "timeline/_comment.html")
            for item in ThreadedComment.objects.all().filter(date_submitted__gte=ago, user__in=friends).order_by("-date_submitted")
            ]

        items = merge(tweets, images, posts, tracks, comments, field="date")
        for index, item in enumerate(items):
            item.index = index + 1

        context['timelineitems'] = group_comments(items)
        context['prefix_sender'] = True
        return context
コード例 #18
0
ファイル: views.py プロジェクト: srogden/django-courses
def teachership(request, course_slug, action, ajax=False):
    course = get_object_or_404(Course, slug=course_slug)
    if not request.user in course.active_teachers():
        return _basic_response(user=request.user, ajax=ajax, 
            message="That action may only be performed by teachers of the \"%s\" \
                course. If you are a teacher, please log in." % course, 
            redirect=reverse("acct_login"))
    if action == "remove":
        if request.method == 'POST':
            if len(course.active_teachers()) <= 1:
                message = "You may not remove yourself as a teacher as you are \
                    the only one left!" % course
            else:
                course.unappoint_teacher(request.user)
                message="You have been removed as a teacher of the \"%s\" course" % course
            return _basic_response(user=request.user, ajax=ajax, message=message, 
                redirect=request.META.get('HTTP_REFERER', course.get_absolute_url()))
        else:
            return HttpResponseForbidden("This URI accepts the POST method only")           
    elif action == "invite":
        if not (request.user in course.owners()) and not ALLOW_TEACHER_PERMISSION_CASCADE:
            return _basic_response(user=request.user, ajax=ajax, 
                message="Only course owners may invite other teachers", 
                redirect=request.META.get('HTTP_REFERER', course.get_absolute_url()))
        if request.method == "POST":
            teachers = User.objects.filter(pk__in=request.POST.getlist(u'teachers'))
            for teacher in teachers:                        
                i = TeachingInvitation(invitor=request.user, invitee=teacher, course=course, 
                    status="I")
                i.save()
            if notification:
                notification.send(teachers, "course_teacher_invitation", {
                    'creator': request.user,
                    'course': course,
                    'uuid': i.uuid
                })
            return _basic_response(user=request.user, ajax=ajax, 
                message="Your invitation has been sent", 
                redirect=request.META.get('HTTP_REFERER', course.get_absolute_url()))
        else:
            return render_to_response("courses/courses/invite_teacher.html", {
                'course': course,
                'friends': [friend for friend in 
                            friend_set_for(request.user) if not 
                            friend in course.active_teachers()]
            }, context_instance=RequestContext(request))
コード例 #19
0
def tagged_photos(request, tagname, template_name="photos/tagged_photos.html"):
    """
    Get the photos with a tag and display them
    """

    image_filter = Q(is_public=True)

    if request.user.is_authenticated():
        image_filter = image_filter | Q(member=request.user) | Q(
            member__in=friend_set_for(request.user))

    photos = TaggedItem.objects.get_by_model(
        Image, tagname).filter(image_filter).order_by("-date_added")
    group, bridge = group_and_bridge(request)
    ctx = group_context(group, bridge)
    ctx.update({"photos": photos, "tag": tagname})
    return render_to_response(template_name, RequestContext(request, ctx))
コード例 #20
0
ファイル: views.py プロジェクト: trb116/pythonanalyzer
    def get_context_data(self, **kwargs):
        context = super(HomePageView, self).get_context_data(**kwargs)
        # reduce the timeline items
        context['timelineitems'] = group_comments(
            context['timelineitems'][:16])
        image_filter = Q(is_public=True)

        if self.request.user.is_authenticated():
            image_filter = image_filter | Q(member=self.request.user) | Q(
                member__in=friend_set_for(self.request.user))
        context['latest_photos'] = Image.objects.all().filter(
            image_filter).order_by("-date_added")[:16]
        context['latest_blogs'] = Post.objects.all().filter(
            status=2).order_by("-publish")[:10]
        context['latest_tracks'] = Track.objects.all().order_by(
            "-created_at")[:6]
        return context
コード例 #21
0
ファイル: views.py プロジェクト: seayoung1112/myactivity
def get_friend_candidates(request, activity_id):
    user = request.user
    activity = Activity.objects.get(pk=activity_id)
    invitee_set = set(activity.invitee.all())
    friend_set = (friend_set_for(user) - invitee_set)
    friend_set.discard(activity.invitor)
    friend_list = list(friend_set)
    paginator = Paginator(friend_list, 10)
    try:
        page = int(request.GET.get('page', 1))
    except ValueError:
        page = 1
    try:
        friends = paginator.page(page)
    except (EmptyPage, InvalidPage):
        friends = paginator.page(paginator.num_pages)

    return render_to_response('share/candidates_page.html', {'users': friends})
コード例 #22
0
ファイル: views.py プロジェクト: amarandon/smeuhsocial
def tagged_photos(request, tagname, template_name="photos/tagged_photos.html"):
    """
    Get the photos with a tag and display them
    """
        
    image_filter = Q(is_public=True)

    if request.user.is_authenticated():
        image_filter = image_filter | Q(member=request.user) | Q(member__in=friend_set_for(request.user))
        
    photos = TaggedItem.objects.get_by_model(Image, tagname).filter(image_filter).order_by("-date_added")   
    group, bridge = group_and_bridge(request)
    ctx = group_context(group, bridge)
    ctx.update({
        "photos": photos,
        "tag": tagname
    })    
    return render(request, template_name, ctx)
コード例 #23
0
ファイル: views.py プロジェクト: amarandon/smeuhsocial
    def get_context_data(self, **kwargs):
        context = super(LegacyHomePageView, self).get_context_data(**kwargs)
        context['latest_tweets'] = lambda: Tweet.objects.all().order_by(
            "-sent")[:12]
        context['latest_blogs'] = lambda: Post.objects.filter(
            status=2).order_by("-publish")[:10]
            
        image_filter = Q(is_public=True)

        if self.request.user.is_authenticated():
            image_filter = image_filter | Q(member=self.request.user) | Q(member__in=friend_set_for(self.request.user))
            
        context['latest_photos'] = lambda: Image.objects.all().filter(image_filter).order_by(
            "-date_added")[:18]
        context['latest_tracks'] = lambda: Track.objects.all().order_by(
            "-created_at")[:6]
        context['prefix_sender'] = True
        return context
コード例 #24
0
ファイル: views.py プロジェクト: trb116/pythonanalyzer
    def get_context_data(self, **kwargs):
        context = super(LegacyHomePageView, self).get_context_data(**kwargs)
        context['latest_tweets'] = lambda: Tweet.objects.all().order_by("-sent"
                                                                        )[:12]
        context['latest_blogs'] = lambda: Post.objects.filter(
            status=2).order_by("-publish")[:10]

        image_filter = Q(is_public=True)

        if self.request.user.is_authenticated():
            image_filter = image_filter | Q(member=self.request.user) | Q(
                member__in=friend_set_for(self.request.user))

        context['latest_photos'] = lambda: Image.objects.all().filter(
            image_filter).order_by("-date_added")[:18]
        context['latest_tracks'] = lambda: Track.objects.all().order_by(
            "-created_at")[:6]
        context['prefix_sender'] = True
        return context
コード例 #25
0
def user_photos(request, username, template_name="photos/user_photos.html"):
    """
    Get the photos of a user and display them
    """

    user = get_object_or_404(User, username=username)

    image_filter = Q(is_public=True)

    if request.user.is_authenticated():
        image_filter = image_filter | Q(member=request.user) | Q(
            member__in=friend_set_for(request.user))

    photos = Image.objects.filter(image_filter, member=user)
    photos = photos.order_by("-date_added")
    group, bridge = group_and_bridge(request)
    ctx = group_context(group, bridge)
    ctx.update({"photos": photos, "username": username})
    return render_to_response(template_name, RequestContext(request, ctx))
コード例 #26
0
ファイル: views.py プロジェクト: fgirault/smeuhsocial
    def get_context_data(self, **kwargs):
        context = super(TimeLineView, self).get_context_data(**kwargs)
        # TODO use a query parameter for the time delta. here is 3 months
        ago = datetime.datetime.now() - datetime.timedelta(90)

        tweets = [
            TimeLineItem(item, item.sent, item.sender, "timeline/_tweet.html")
            for item in Tweet.objects.all().filter(sent__gte=ago).order_by("-sent")
            ]

        posts = [
            TimeLineItem(item, item.updated_at, item.author, "timeline/_post.html")
            for item in Post.objects.all().filter(publish__gte=ago, status=2).order_by("-publish")
            ]

        image_filter = Q(is_public=True)

        if self.request.user.is_authenticated():
            image_filter = image_filter | Q(member=self.request.user) | Q(member__in=friend_set_for(self.request.user))
        
        images = [
            TimeLineItem(item, item.date_added, item.member, "timeline/_photo.html")
            for item in Image.objects.all().filter(image_filter).filter(date_added__gte=ago).order_by("-date_added")
            ]        

        tracks = [
            TimeLineItem(item, item.updated_at, item.user, "timeline/_track.html")
            for item in Track.objects.all().filter(created_at__gte=ago).order_by("-created_at")
            ]

        comments = [
            TimeLineItem(item, item.date_submitted, item.user, "timeline/_comment.html")
            for item in ThreadedComment.objects.all().filter(date_submitted__gte=ago).order_by("-date_submitted")
            ]

        items = merge(tweets, images, posts, tracks, comments, field="date")
        for index, item in enumerate(items):
            item.index = index

        context['timelineitems'] = group_comments(items)
        context['posts'] = posts
        context['prefix_sender'] = True
        return context
コード例 #27
0
ファイル: views.py プロジェクト: amarandon/smeuhsocial
def details(request, id, template_name="photos/details.html"):
    """
    show the photo details
    """
    photos = Image.objects.all()
    photos = photos.filter(pool__object_id=None)
    

    image_filter = Q(is_public=True)

    if request.user.is_authenticated():
        # allow owner and friend to see a private photo
        image_filter = image_filter | Q(member=request.user) | Q(member__in=friend_set_for(request.user))
        
    try:
        photo = photos.filter(image_filter, id=id)[0]
    except IndexError:                            
        raise Http404
        
    previous_photo_id = get_first_id_or_none(                                             
        photos.filter(image_filter, id__lt=photo.id).order_by('-id')
        )
    
    next_photo_id = get_first_id_or_none(
        photos.filter(image_filter, id__gt=photo.id).order_by('id')
        )         
    
            
    ctx = {
        "photo": photo,
        "photo_url": request.build_absolute_uri(photo.get_display_url()),
        "url": request.build_absolute_uri(),
        "is_me": photo.member == request.user,
        "previous_photo_id": previous_photo_id,
        "next_photo_id": next_photo_id,
    }
    
    return render(request, template_name, ctx)
コード例 #28
0
def sync_chatbox(request, target):
    """
    Depending on the target argument value, the view either returns
    new chat requests for the logged in user or a list of online users,
    provided by the useractivity app.
    """
    if target == "chat_requests":
        now = datetime.now()

        # Checking for the timestamp in session data, explanations
        # are below.
        timestamp = request.session.get("im:chat_requests:sync", now)
        chat_requests = ChatRequest.objects.incoming(
            request.user,
            timestamp,
        )
        data = map(
            lambda chat_request: render_to(request, "im/chat_request.html",
                                           {"chat_request": chat_request}),
            chat_requests)

        # Saving last check timestamp in session data, so we can later
        # determine which requests were already sent to the browser.
        request.session["im:chat_requests:sync"] = now
    elif target == "online_users":
        friends = friend_set_for(request.user)
        online_users = get_online_users()
        if request.user in online_users:
            online_users.remove(request.user)
        online_friends = online_users & friends
        online_others = online_users - friends

        data = render_to(request, "im/userlist.html", {
            "friends": online_friends,
            "others": online_others
        })

    return json_response(data)
コード例 #29
0
def friends_objects(request, template_name, friends_objects_function, extra_context={}):
    """
    Display friends' objects.
    
    This view takes a template name and a function. The function should
    take an iterator over users and return an iterator over objects
    belonging to those users. This iterator over objects is then passed
    to the template of the given name as ``object_list``.
    
    The template is also passed variable defined in ``extra_context``
    which should be a dictionary of variable names to functions taking a
    request object and returning the value for that variable.
    """
    
    friends = friend_set_for(request.user)
    
    dictionary = {
        "object_list": friends_objects_function(friends),
    }
    for name, func in extra_context.items():
        dictionary[name] = func(request)
    
    return render_to_response(template_name, dictionary, context_instance=RequestContext(request))
コード例 #30
0
def most_viewed(request, template_name="photos/latest.html"):
    """
    latest photos
    """

    group, bridge = group_and_bridge(request)

    photos = Image.objects.filter(
        Q(is_public=True) | Q(member=request.user)
        | Q(member__in=friend_set_for(request.user)))

    if group:
        photos = group.content_objects(photos,
                                       join="pool",
                                       gfk_field="content_object")
    else:
        photos = photos.filter(pool__object_id=None)

    photos = photos.order_by("-view_count")

    ctx = group_context(group, bridge)
    ctx.update({"photos": photos, "title": _("Most Viewed Photos")})

    return render_to_response(template_name, RequestContext(request, ctx))
コード例 #31
0
ファイル: views.py プロジェクト: trb116/pythonanalyzer
    def get_context_data(self, **kwargs):
        context = super(TagHomePageView, self).get_context_data(**kwargs)
        tag_instance = get_object_or_404(Tag,
                                         name__iexact=context.get("tagname"))

        context['tag'] = tag = tag_instance.name

        # ago = datetime.datetime.now() - datetime.timedelta(30)

        tweets = [
            TimeLineItem(item, item.sent, item.sender, "timeline/_tweet.html")
            for item in TaggedItem.objects.get_by_model(Tweet, tag).order_by(
                "-sent")[:16]
        ]

        context['latest_blogs'] = TaggedItem.objects.get_by_model(
            Post, tag).filter(status=2).order_by("-publish")[:10]

        posts = [
            TimeLineItem(item, item.publish, item.author,
                         "timeline/_post.html")
            for item in context['latest_blogs']
        ]

        image_filter = Q(is_public=True)

        if self.request.user.is_authenticated():
            image_filter = image_filter | Q(member=self.request.user) | Q(
                member__in=friend_set_for(self.request.user))

        context['latest_photos'] = TaggedItem.objects.get_by_model(
            Image, tag).filter(image_filter).order_by("-date_added")[:16]

        images = [
            TimeLineItem(item, item.date_added, item.member,
                         "timeline/_photo.html")
            for item in context['latest_photos']
        ]

        context['latest_tracks'] = TaggedItem.objects.get_by_model(
            Track, tag).order_by("-created_at")

        tracks = [
            TimeLineItem(item, item.updated_at, item.user,
                         "timeline/_track.html")
            for item in context['latest_tracks']
        ]

        comments = [
            TimeLineItem(item, item.date_submitted, item.user,
                         "timeline/_comment.html")
            for item in TaggedItem.objects.get_by_model(
                ThreadedComment, tag).order_by("-date_submitted")
        ]

        # no tag for comment yet. so : no comment :)

        # Tag.objects.get_for_object(self.obj.resolve(context))

        items = merge(tweets, images, posts, tracks, comments,
                      field="date")[:16]
        for index, item in enumerate(items):
            item.index = index + 1
        context['timelineitems'] = group_comments(items)
        context['prefix_sender'] = True
        return context
コード例 #32
0
def teachership(request, course_slug, action, ajax=False):
    course = get_object_or_404(Course, slug=course_slug)
    if not request.user in course.active_teachers():
        return _basic_response(
            user=request.user,
            ajax=ajax,
            message=
            "That action may only be performed by teachers of the \"%s\" \
                course. If you are a teacher, please log in." % course,
            redirect=reverse("acct_login"))
    if action == "remove":
        if request.method == 'POST':
            if len(course.active_teachers()) <= 1:
                message = "You may not remove yourself as a teacher as you are \
                    the only one left!" % course
            else:
                course.unappoint_teacher(request.user)
                message = "You have been removed as a teacher of the \"%s\" course" % course
            return _basic_response(user=request.user,
                                   ajax=ajax,
                                   message=message,
                                   redirect=request.META.get(
                                       'HTTP_REFERER',
                                       course.get_absolute_url()))
        else:
            return HttpResponseForbidden(
                "This URI accepts the POST method only")
    elif action == "invite":
        if not (request.user
                in course.owners()) and not ALLOW_TEACHER_PERMISSION_CASCADE:
            return _basic_response(
                user=request.user,
                ajax=ajax,
                message="Only course owners may invite other teachers",
                redirect=request.META.get('HTTP_REFERER',
                                          course.get_absolute_url()))
        if request.method == "POST":
            teachers = User.objects.filter(
                pk__in=request.POST.getlist(u'teachers'))
            for teacher in teachers:
                i = TeachingInvitation(invitor=request.user,
                                       invitee=teacher,
                                       course=course,
                                       status="I")
                i.save()
            if notification:
                notification.send(teachers, "course_teacher_invitation", {
                    'creator': request.user,
                    'course': course,
                    'uuid': i.uuid
                })
            return _basic_response(user=request.user,
                                   ajax=ajax,
                                   message="Your invitation has been sent",
                                   redirect=request.META.get(
                                       'HTTP_REFERER',
                                       course.get_absolute_url()))
        else:
            return render_to_response("courses/courses/invite_teacher.html", {
                'course':
                course,
                'friends': [
                    friend for friend in friend_set_for(request.user)
                    if not friend in course.active_teachers()
                ]
            },
                                      context_instance=RequestContext(request))
コード例 #33
0
ファイル: models.py プロジェクト: SuLab/biogps_core
 def is_friends_with(self, user2):
     '''Given a second user object, returns True if the two users are friends.
     '''
     from friends.models import friend_set_for
     return user2 in friend_set_for(self)
コード例 #34
0
ファイル: views.py プロジェクト: trb116/pythonanalyzer
    def get_context_data(self, **kwargs):
        context = super(UserPageView, self).get_context_data(**kwargs)
        name = context.get('username', None)
        limit = 64
        if name:
            user = other_user = get_object_or_404(User, username=name)
        else:
            user = other_user = self.request.user

        if self.request.user == other_user:
            context['is_me'] = True
            context['is_friend'] = False
        elif self.request.user.is_authenticated():
            context['is_friend'] = Friendship.objects.are_friends(
                self.request.user, other_user)
            context['is_following'] = Following.objects.is_following(
                self.request.user, other_user)
        context['other_friends'] = Friendship.objects.friends_for_user(
            other_user)
        context['other_user'] = other_user

        tweets = [
            TimeLineItem(item, item.sent, item.sender, "timeline/_tweet.html")
            for item in Tweet.objects.all().filter(
                sender_id=user.id, sender_type__model="user").order_by("-sent")
            [:limit]
        ]

        context['latest_blogs'] = Post.objects.all().filter(
            status=2, author=user).order_by("-publish")[:limit]

        posts = [
            TimeLineItem(item, item.updated_at, item.author,
                         "timeline/_post.html")
            for item in context['latest_blogs']
        ]

        image_filter = Q(is_public=True, member=user)

        if self.request.user.is_authenticated():
            image_filter = image_filter | Q(
                member=user, member__in=friend_set_for(self.request.user))

        context['latest_photos'] = Image.objects.all().filter(
            image_filter).order_by("-date_added")[:limit]

        images = [
            TimeLineItem(item, item.date_added, item.member,
                         "timeline/_photo.html")
            for item in context['latest_photos']
        ]

        context['latest_tracks'] = Track.objects.all().filter(
            user=user).order_by("-created_at")[:limit]

        tracks = [
            TimeLineItem(item, item.updated_at, item.user,
                         "timeline/_track.html")
            for item in context['latest_tracks']
        ]

        comments = [
            TimeLineItem(item, item.date_submitted, item.user,
                         "timeline/_comment.html")
            for item in ThreadedComment.objects.all().filter(
                user=user).order_by("-date_submitted")[:limit]
        ]

        items = merge(tweets, images, posts, tracks, comments, field="date")
        for index, item in enumerate(items):
            item.index = index + 1
        context['timelineitems'] = group_comments(items)[:limit]
        context['prefix_sender'] = True
        return context
コード例 #35
0
ファイル: views.py プロジェクト: trb116/pythonanalyzer
    def get_context_data(self, **kwargs):
        context = super(UserHomePageView, self).get_context_data(**kwargs)

        other_friends = None
        username = name = context.get('username', None)

        if name:
            user = other_user = get_object_or_404(User, username=name)
        else:
            user = other_user = self.request.user

        if self.request.user == other_user:
            context['is_me'] = True
            is_friend = False
        elif self.request.user.is_authenticated():
            is_friend = context['is_friend'] = Friendship.objects.are_friends(
                self.request.user, other_user)
            context['is_following'] = Following.objects.is_following(
                self.request.user, other_user)
        else:
            is_friend = False
        context['other_friends'] = Friendship.objects.friends_for_user(
            other_user)

        context['other_user'] = other_user
        tweets = [
            TimeLineItem(item, item.sent, item.sender, "timeline/_tweet.html")
            for item in Tweet.objects.all().filter(
                sender_id=user.id, sender_type__model="user").order_by("-sent")
            [:32]
        ]

        context['latest_blogs'] = Post.objects.all().filter(
            status=2, author=user).order_by("-publish")[:32]

        posts = [
            TimeLineItem(item, item.updated_at, item.author,
                         "timeline/_post.html")
            for item in context['latest_blogs']
        ]

        image_filter = Q(is_public=True, member=user)

        if self.request.user.is_authenticated():
            image_filter = image_filter | Q(
                member=user, member__in=friend_set_for(self.request.user))

        context['latest_photos'] = Image.objects.all().filter(
            image_filter).order_by("-date_added")[:32]

        images = [
            TimeLineItem(item, item.date_added, item.member,
                         "timeline/_photo.html")
            for item in context['latest_photos']
        ]

        context['latest_tracks'] = Track.objects.all().filter(
            user=user).order_by("-created_at")[:32]

        tracks = [
            TimeLineItem(item, item.updated_at, item.user,
                         "timeline/_track.html")
            for item in context['latest_tracks']
        ]

        comments = [
            TimeLineItem(item, item.date_submitted, item.user,
                         "timeline/_comment.html")
            for item in ThreadedComment.objects.all().filter(
                user=user).order_by("-date_submitted")[:32]
        ]

        items = merge(tweets, images, posts, tracks, comments,
                      field="date")[:16]
        for index, item in enumerate(items):
            item.index = index + 1
        context['timelineitems'] = group_comments(items)
        context['prefix_sender'] = True

        invite_form = None
        if is_friend:
            previous_invitations_to = None
            previous_invitations_from = None
            if self.request.method == "POST":
                if self.request.POST.get(
                        "action"
                ) == "remove":  # @@@ perhaps the form should just post to friends and be redirected here
                    Friendship.objects.remove(self.request.user, other_user)
                    messages.add_message(
                        self.request, messages.SUCCESS,
                        ugettext("You have removed %(from_user)s from friends")
                        % {"from_user": other_user})
                    is_friend = False
                    invite_form = InviteFriendForm(
                        self.request.user, {
                            "to_user": username,
                            "message": ugettext("Let's be friends!"),
                        })

        else:
            if self.request.user.is_authenticated(
            ) and self.request.method == "POST":
                pass
            else:
                invite_form = InviteFriendForm(
                    self.request.user, {
                        "to_user": username,
                        "message": ugettext("Let's be friends!"),
                    })
                previous_invitations_to = None
                previous_invitations_from = None

        context['invite_form'] = invite_form
        context['previous_invitations_to'] = previous_invitations_to
        context['previous_invitations_from'] = previous_invitations_from
        context['other_friends'] = other_friends
        return context
コード例 #36
0
ファイル: views.py プロジェクト: amarandon/smeuhsocial
    def get_context_data(self, **kwargs):
        context = super(UserHomePageView, self).get_context_data(**kwargs)
        
        other_friends = None
        username = name = context.get('username', None)

        if name:
            user = other_user = get_object_or_404(User, username=name)
        else:
            user = other_user = self.request.user

        if self.request.user == other_user:
            context['is_me'] = True
            is_friend = False
        elif self.request.user.is_authenticated():
            is_friend = context['is_friend'] = Friendship.objects.are_friends(self.request.user, other_user)
            context['is_following'] = Following.objects.is_following(self.request.user, other_user)
        else:
            is_friend = False
        context['other_friends'] = Friendship.objects.friends_for_user(other_user)

        context['other_user'] = other_user
        tweets = [
            TimeLineItem(item, item.sent, item.sender, "timeline/_tweet.html")
            for item in Tweet.objects.all().filter(sender_id=user.id, sender_type__model="user").order_by("-sent")[:32]
            ]

        context['latest_blogs'] = Post.objects.all().filter(status=2, author=user).order_by("-publish")[:32]

        posts = [
            TimeLineItem(item, item.updated_at, item.author, "timeline/_post.html")
            for item in context['latest_blogs']
            ]

        image_filter = Q(is_public=True, member=user)

        if self.request.user.is_authenticated():
            image_filter = image_filter | Q(member=user, member__in=friend_set_for(self.request.user))

        context['latest_photos'] = Image.objects.all().filter(image_filter).order_by("-date_added")[:32]

        images = [
            TimeLineItem(item, item.date_added, item.member, "timeline/_photo.html")
            for item in context['latest_photos']
            ]

        context['latest_tracks'] = Track.objects.all().filter(user=user).order_by("-created_at")[:32]

        tracks = [
            TimeLineItem(item, item.updated_at, item.user, "timeline/_track.html")
            for item in context['latest_tracks']
            ]

        comments = [
            TimeLineItem(item, item.date_submitted, item.user, "timeline/_comment.html")
            for item in ThreadedComment.objects.all().filter(user=user).order_by("-date_submitted")[:32]
            ]
        
        items = merge(tweets, images, posts, tracks, comments, field="date")[:16]
        for index, item in enumerate(items):
            item.index = index + 1
        context['timelineitems'] = group_comments(items)
        context['prefix_sender'] = True


        invite_form = None
        if is_friend:
            previous_invitations_to = None
            previous_invitations_from = None
            if self.request.method == "POST":
                if self.request.POST.get("action") == "remove":  # @@@ perhaps the form should just post to friends and be redirected here
                    Friendship.objects.remove(self.request.user, other_user)
                    messages.add_message(self.request, messages.SUCCESS,
                        ugettext("You have removed %(from_user)s from friends") % {
                            "from_user": other_user
                        }
                    )
                    is_friend = False
                    invite_form = InviteFriendForm(self.request.user, {
                        "to_user": username,
                        "message": ugettext("Let's be friends!"),
                    })

        else:
            if self.request.user.is_authenticated() and self.request.method == "POST":
                pass
            else:
                invite_form = InviteFriendForm(self.request.user, {
                    "to_user": username,
                    "message": ugettext("Let's be friends!"),
                })
                previous_invitations_to = None
                previous_invitations_from = None

        context['invite_form'] = invite_form
        context['previous_invitations_to'] = previous_invitations_to
        context['previous_invitations_from'] = previous_invitations_from
        context['other_friends'] = other_friends
        return context
コード例 #37
0
ファイル: feeds.py プロジェクト: joskid/smeuhsocial
 def items(self, user):
     friends = friend_set_for(user)
     friend_ids = [friend.id for friend in friends] + [user.id]
     return Tweet.objects.filter(sender_id__in=friend_ids, sender_type__name="user")