Exemple #1
0
def invite_friend(request,
                  username,
                  redirect_to_view=None,
                  message=_("I would like to add you to my friends.")):
    """
    Invite user to be user friend.
    """
    friend = get_object_or_404(User, username=username)
    if request.method == "POST":
        form = InviteFriendForm(data=request.POST, user=request.user)
        if form.is_valid():
            form.save()
            to_user = User.objects.get(username=request.POST["to_user"])
            inviting_friend.send(FriendshipInvitation,
                                 request=request,
                                 to_user=to_user)
            messages.success(
                request,
                _("Friendship invitation for %(username)s was created.") %
                {'username': username},
                fail_silently=True)
            if not redirect_to_view:
                redirect_to_view = list_sent_invitations
            return redirect(redirect_to_view)
    else:
        form = InviteFriendForm(initial={
            'to_user': username,
            'message': message
        })
    return render_to_response('friends/friend_invite.html', {
        'form': form,
        'friend': friend
    },
                              context_instance=RequestContext(request))
Exemple #2
0
    def post(self, *args, **kw):
        if self.request.POST.get("action") == "invite":
            username = self.request.POST.get("to_user")
            other_user = get_object_or_404(User, username=username)

            invite_form = InviteFriendForm(self.request.user,
                                           self.request.POST)
            if invite_form.is_valid():
                invite_form.save()
                messages.success(
                    self.request,
                    _("Friendship requested with %(username)s") %
                    {'username': invite_form.cleaned_data['to_user']})
        elif self.request.POST.get("action") == "remove":
            username = kw['username']
            other_user = get_object_or_404(User, username=username)
            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})
        else:
            username = kw['username']
            other_user = get_object_or_404(User, username=username)
            invite_form = InviteFriendForm(
                self.request.user, {
                    "to_user": username,
                    "message": ugettext("Let's be friends!"),
                })
            invitation_id = self.request.POST.get("invitation", None)
            if self.request.POST.get("action") == "accept":
                try:
                    invitation = FriendshipInvitation.objects.get(
                        id=invitation_id)
                    if invitation.to_user == self.equest.user:
                        invitation.accept()
                        messages.add_message(
                            self.request, messages.SUCCESS,
                            ugettext(
                                "You have accepted the friendship request from %(from_user)s"
                            ) % {"from_user": invitation.from_user})
                except FriendshipInvitation.DoesNotExist:
                    pass
            elif self.request.POST.get("action") == "decline":
                try:
                    invitation = FriendshipInvitation.objects.get(
                        id=invitation_id)
                    if invitation.to_user == self.request.user:
                        invitation.decline()
                        messages.add_message(
                            self.request, messages.SUCCESS,
                            ugettext(
                                "You have declined the friendship request from %(from_user)s"
                            ) % {"from_user": invitation.from_user})
                except FriendshipInvitation.DoesNotExist:
                    pass

        return HttpResponseRedirect(
            reverse("timeline.views.user_home", kwargs={"username": username}))
Exemple #3
0
def profile(request,
            username,
            template_name="profiles/profile.html",
            extra_context=None):

    if extra_context is None:
        extra_context = {}

    other_user = get_object_or_404(User, username=username)

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

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

    else:
        if request.user.is_authenticated() and request.method == "POST":
            if request.POST.get(
                    "action"
            ) == "invite":  # @@@ perhaps the form should just post to friends and be redirected here
                invite_form = InviteFriendForm(request.user, request.POST)
                if invite_form.is_valid():
                    invite_form.save()
            else:
                invite_form = InviteFriendForm(
                    request.user, {
                        "to_user": username,
                        "message": ugettext("Let's be friends!"),
                    })
                invitation_id = request.POST.get("invitation", None)
                if request.POST.get(
                        "action"
                ) == "accept":  # @@@ perhaps the form should just post to friends and be redirected here
                    try:
                        invitation = FriendshipInvitation.objects.get(
                            id=invitation_id)
                        if invitation.to_user == request.user:
                            invitation.accept()
                            messages.add_message(
                                request, messages.SUCCESS,
                                ugettext(
                                    "You have accepted the friendship request from %(from_user)s"
                                ) % {"from_user": invitation.from_user})
                            is_friend = True
                            other_friends = Friendship.objects.friends_for_user(
                                other_user)
                    except FriendshipInvitation.DoesNotExist:
                        pass
                elif request.POST.get(
                        "action"
                ) == "decline":  # @@@ perhaps the form should just post to friends and be redirected here
                    try:
                        invitation = FriendshipInvitation.objects.get(
                            id=invitation_id)
                        if invitation.to_user == request.user:
                            invitation.decline()
                            messages.add_message(
                                request, messages.SUCCESS,
                                ugettext(
                                    "You have declined the friendship request from %(from_user)s"
                                ) % {"from_user": invitation.from_user})
                            other_friends = Friendship.objects.friends_for_user(
                                other_user)
                    except FriendshipInvitation.DoesNotExist:
                        pass
            previous_invitations_to = FriendshipInvitation.objects.invitations(
                to_user=other_user, from_user=request.user)
            previous_invitations_from = FriendshipInvitation.objects.invitations(
                to_user=request.user, from_user=other_user)
        else:
            invite_form = InviteFriendForm(
                request.user, {
                    "to_user": username,
                    "message": ugettext("Let's be friends!"),
                })
            previous_invitations_to = None
            previous_invitations_from = None

    return render_to_response(
        template_name,
        dict(
            {
                "is_me": is_me,
                "is_friend": is_friend,
                "is_following": is_following,
                "other_user": other_user,
                "other_friends": other_friends,
                "invite_form": invite_form,
                "previous_invitations_to": previous_invitations_to,
                "previous_invitations_from": previous_invitations_from,
            }, **extra_context),
        context_instance=RequestContext(request))
Exemple #4
0
def profile(request, username, template_name="profiles/profile.html", extra_context=None):
    if extra_context is None:
        extra_context = {}
    other_user = get_object_or_404(User, username=username)
    if request.user.is_authenticated():
        is_friend = Friendship.objects.are_friends(request.user, other_user)
        is_following = Following.objects.is_following(request.user, other_user)
        other_friends = Friendship.objects.friends_for_user(other_user)
        if request.user == other_user:
            is_me = True
        else:
            is_me = False
    else:
        other_friends = []
        is_friend = False
        is_me = False
        is_following = False
    
    if is_friend:
        invite_form = None
        previous_invitations_to = None
        previous_invitations_from = None
        if request.method == "POST":
            if request.POST["action"] == "remove":
                Friendship.objects.remove(request.user, other_user)
                request.user.message_set.create(message=_("You have removed %(from_user)s from friends") % {'from_user': other_user})
                is_friend = False
                invite_form = InviteFriendForm(request.user, {
                    'to_user': username,
                    'message': ugettext("Let's be friends!"),
                })

    else:
        if request.user.is_authenticated() and request.method == "POST":
            if request.POST["action"] == "invite":
                invite_form = InviteFriendForm(request.user, request.POST)
                if invite_form.is_valid():
                    invite_form.save()
            else:
                invite_form = InviteFriendForm(request.user, {
                    'to_user': username,
                    'message': ugettext("Let's be friends!"),
                })
                invitation_id = request.POST.get("invitation", "")
                if request.POST["action"] == "accept": # @@@ perhaps the form should just post to friends and be redirected here
                    try:
                        invitation = FriendshipInvitation.objects.get(id=invitation_id)
                        if invitation.to_user == request.user:
                            invitation.accept()
                            request.user.message_set.create(message=_("You have accepted the friendship request from %(from_user)s") % {'from_user': invitation.from_user})
                            is_friend = True
                            other_friends = Friendship.objects.friends_for_user(other_user)
                    except FriendshipInvitation.DoesNotExist:
                        pass
                elif request.POST["action"] == "decline":
                    try:
                        invitation = FriendshipInvitation.objects.get(id=invitation_id)
                        if invitation.to_user == request.user:
                            invitation.decline()
                            request.user.message_set.create(message=_("You have declined the friendship request from %(from_user)s") % {'from_user': invitation.from_user})
                            other_friends = Friendship.objects.friends_for_user(other_user)
                    except FriendshipInvitation.DoesNotExist:
                        pass
        else:
            invite_form = InviteFriendForm(request.user, {
                'to_user': username,
                'message': ugettext("Let's be friends!"),
            })
    if request.user.is_authenticated():
        previous_invitations_to = FriendshipInvitation.objects.filter(to_user=other_user, from_user=request.user).exclude(status=8).exclude(status=6)
        previous_invitations_from = FriendshipInvitation.objects.filter(to_user=request.user, from_user=other_user).exclude(status=8).exclude(status=6)
    
    if is_me:
        if request.method == "POST":
            if request.POST["action"] == "update":
                profile_form = ProfileForm(request.POST, instance=other_user.get_profile())
                if profile_form.is_valid():
                    profile = profile_form.save(commit=False)
                    profile.user = other_user
                    profile.save()
            else:
                profile_form = ProfileForm(instance=other_user.get_profile())
        else:
            profile_form = ProfileForm(instance=other_user.get_profile())
    else:
        profile_form = None

    total_duration = timedelta()
    total_distance = 0
    total_avg_speed = 0
    total_avg_hr = 0

    nr_trips = 0
    nr_hr_trips = 0
    longest_trip = 0
    avg_length = 0
    avg_duration = 0

    bmidataseries = ''
    bmiline = ''
    pulsedataseries = ""
    tripdataseries = ""
    avgspeeddataseries = ""
    avghrdataseries = ""
    ftpdataseries = ''
    height = other_user.get_profile().height
    if height:
        height = float(other_user.get_profile().height)/100
        weightqs = other_user.get_profile().userprofiledetail_set.filter(weight__isnull=False).order_by('time')
        for wtuple in weightqs.values_list('time', 'weight'):
            bmidataseries += '[%s, %s],' % (datetime2jstimestamp(wtuple[0]), wtuple[1]/(height*height))
            bmiline += '[%s, 25],' %datetime2jstimestamp(wtuple[0])

    pulseqs = other_user.get_profile().userprofiledetail_set.filter(resting_hr__isnull=False).order_by('time')
    for hrtuple in pulseqs.values_list('time', 'resting_hr'):
        pulsedataseries += '[%s, %s],' % (datetime2jstimestamp(hrtuple[0]), hrtuple[1])

    ftpqs = other_user.get_profile().userprofiledetail_set.filter(ftp__isnull=False).order_by('time')
    for ftuple in ftpqs.values_list('time', 'ftp'):
        ftpdataseries += '[%s, %s],' % (datetime2jstimestamp(ftuple[0]), ftuple[1])

    exerciseqs = other_user.exercise_set.select_related('route','exercise_type').order_by('date')
    exerciseqs_dataseries = other_user.exercise_set.select_related('route','exercise_type').order_by('date')[:7]

    i = 0

    for trip in reversed(exerciseqs):
        if trip.avg_speed and trip.exercise_type.name=="Cycling":
            # only increase counter if trip has speed
            avgspeeddataseries += '[%s, %s],' % (datetime2jstimestamp(trip.date), trip.avg_speed)
            i += 1
        if i > 7:
            break

    i = 0

    for trip in reversed(exerciseqs):
        if trip.avg_hr:
            avghrdataseries += '[%s, %s],' % (datetime2jstimestamp(trip.date), trip.avg_hr)
            i += 1
        if i > 7:
            break

    for trip in exerciseqs:
        if trip.route:
            tripdataseries += '[%s, %s],' % ( nr_trips, trip.route.distance)

            if trip.route.distance > longest_trip:
                longest_trip = round(trip.route.distance)
            total_distance += trip.route.distance

        if trip.duration:
            total_duration += trip.duration
        if trip.avg_speed:
            # only increase counter if trip has speed
            total_avg_speed += trip.avg_speed
            nr_trips += 1
    if total_avg_speed:
        total_avg_speed = total_avg_speed/nr_trips

    for event in exerciseqs:
        if event.avg_hr:
            total_avg_hr += event.avg_hr
            nr_hr_trips += 1

    if total_avg_hr:
        total_avg_hr = total_avg_hr/nr_hr_trips

    total_kcals = max(0, other_user.exercise_set.aggregate(Sum('kcal'))['kcal__sum'])

# TODO fix total_duration for hike and otherexercise
# Todo filter ?

    for cycletrip in exerciseqs:
        if exerciseqs[0].date:
            days_since_start = (datetime.now() - datetime(exerciseqs[0].date.year, exerciseqs[0].date.month, exerciseqs[0].date.day, 0, 0, 0)).days
# TODO check in exercise and hike for first
            if days_since_start == 0: # if they only have one trip and it was today
                days_since_start = 1
            km_per_day = total_distance / days_since_start
            kcal_per_day = total_kcals / days_since_start
            time_per_day = total_duration / days_since_start

    

    latest_exercises = other_user.exercise_set.select_related('route','exercise_type', 'user').order_by('-date')[:20]


    return render_to_response(template_name, locals(),
            context_instance=RequestContext(request))
Exemple #5
0
    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
Exemple #6
0
Fichier : views.py Projet : cjs/bme
def profile(request, username, template_name="profiles/profile.html"):
    other_user = get_object_or_404(User, username=username)
    if request.user.is_authenticated():
        is_friend = Friendship.objects.are_friends(request.user, other_user)
        is_following = Following.objects.is_following(request.user, other_user)
        other_friends = Friendship.objects.friends_for_user(other_user)
        if request.user == other_user:
            is_me = True
        else:
            is_me = False
    else:
        other_friends = []
        is_friend = False
        is_me = False
        is_following = False

    if is_friend:
        invite_form = None
        previous_invitations_to = None
        previous_invitations_from = None
    else:
        if request.user.is_authenticated() and request.method == "POST":
            if request.POST["action"] == "invite":
                invite_form = InviteFriendForm(request.user, request.POST)
                if invite_form.is_valid():
                    invite_form.save()
            else:
                invite_form = InviteFriendForm(
                    request.user, {
                        'to_user': username,
                        'message': ugettext("Let's be friends!"),
                    })
                if request.POST[
                        "action"] == "accept":  # @@@ perhaps the form should just post to friends and be redirected here
                    invitation_id = request.POST["invitation"]
                    try:
                        invitation = FriendshipInvitation.objects.get(
                            id=invitation_id)
                        if invitation.to_user == request.user:
                            invitation.accept()
                            request.user.message_set.create(message=_(
                                "You have accepted the friendship request from %(from_user)s"
                            ) % {'from_user':
                                 invitation.from_user})
                            is_friend = True
                            other_friends = Friendship.objects.friends_for_user(
                                other_user)
                    except FriendshipInvitation.DoesNotExist:
                        pass
        else:
            invite_form = InviteFriendForm(
                request.user, {
                    'to_user': username,
                    'message': ugettext("Let's be friends!"),
                })
    previous_invitations_to = FriendshipInvitation.objects.filter(
        to_user=other_user, from_user=request.user)
    previous_invitations_from = FriendshipInvitation.objects.filter(
        to_user=request.user, from_user=other_user)

    if is_me:
        if request.method == "POST":
            if request.POST["action"] == "update":
                profile_form = ProfileForm(request.POST,
                                           instance=other_user.get_profile())
                if profile_form.is_valid():
                    profile = profile_form.save(commit=False)
                    profile.user = other_user
                    profile.save()
            else:
                profile_form = ProfileForm(instance=other_user.get_profile())
        else:
            profile_form = ProfileForm(instance=other_user.get_profile())
    else:
        profile_form = None

    return render_to_response(
        template_name, {
            "profile_form": profile_form,
            "is_me": is_me,
            "is_friend": is_friend,
            "is_following": is_following,
            "other_user": other_user,
            "other_friends": other_friends,
            "invite_form": invite_form,
            "previous_invitations_to": previous_invitations_to,
            "previous_invitations_from": previous_invitations_from,
        },
        context_instance=RequestContext(request))