コード例 #1
0
def tag_courses_view(request, tag_id):
    courses, response = can_view_courses_list(request)
    if response is not None:
        return response
    courses = courses.filter(coursetag__tag__pk=tag_id)

    dashboard_accessed.send(sender=None, request=request, data=None)

    courses_list = []
    for course in courses:
        obj = {}
        obj['course'] = course
        access_detail, response = can_view_course_detail(request, course.id)
        if access_detail is not None:
            obj['access_detail'] = True
        else:
            obj['access_detail'] = False
        courses_list.append(obj)
    tag_list = Tag.objects.all().order_by('name')
    return render_to_response('oppia/course/courses-list.html', {
        'courses_list': courses_list,
        'tag_list': tag_list,
        'current_tag': id
    },
                              context_instance=RequestContext(request))
コード例 #2
0
def tag_courses_view(request, tag_id):
    courses = can_view_courses_list(request)

    courses = courses.filter(coursetag__tag__pk=tag_id)

    dashboard_accessed.send(sender=None, request=request, data=None)
    return render_courses_list(request, courses, {'current_tag': tag_id})
コード例 #3
0
def user_activity(request, user_id):

    view_user, response = get_user(request, user_id)
    if response is not None:
        return response

    dashboard_accessed.send(sender=None, request=request, data=None)

    cohort_courses, other_courses, all_courses = get_user_courses(
        request, view_user)

    courses = []
    for course in all_courses:
        data = {
            'course':
            course,
            'no_quizzes_completed':
            course.get_no_quizzes_completed(course, view_user),
            'pretest_score':
            course.get_pre_test_score(course, view_user),
            'no_activities_completed':
            course.get_activities_completed(course, view_user),
            'no_quizzes_completed':
            course.get_no_quizzes_completed(course, view_user),
            'no_points':
            course.get_points(course, view_user),
            'no_badges':
            course.get_badges(course, view_user),
        }
        courses.append(data)

    activity = []
    start_date = timezone.now() - datetime.timedelta(days=31)
    end_date = timezone.now()
    no_days = (end_date - start_date).days + 1

    course_ids = list(
        chain(cohort_courses.values_list('id', flat=True),
              other_courses.values_list('id', flat=True)))
    trackers = Tracker.objects.filter(course__id__in=course_ids,
                                      user=view_user,
                                      tracker_date__gte=start_date,
                                      tracker_date__lte=end_date) \
                                      .extra({'activity_date':"date(tracker_date)"}) \
                                      .values('activity_date') \
                                      .annotate(count=Count('id'))
    for i in range(0, no_days, +1):
        temp = start_date + datetime.timedelta(days=i)
        count = next(
            (dct['count']
             for dct in trackers if dct['activity_date'] == temp.date()), 0)
        activity.append([temp.strftime("%d %b %Y"), count])

    return render_to_response('oppia/profile/user-scorecard.html', {
        'view_user': view_user,
        'courses': courses,
        'activity_graph_data': activity
    },
                              context_instance=RequestContext(request))
コード例 #4
0
def tag_courses_view(request, tag_id):
    courses, response = can_view_courses_list(request)
    if response is not None:
        return response
    courses = courses.filter(coursetag__tag__pk=tag_id)

    dashboard_accessed.send(sender=None, request=request, data=None)
    return render_courses_list(request, courses, {"current_tag": tag_id})
コード例 #5
0
def recent_activity(request, course_id):

    course, response = can_view_course_detail(request, course_id)

    if response is not None:
        return response

    dashboard_accessed.send(sender=None, request=request, data=course)

    start_date = datetime.datetime.now() - datetime.timedelta(days=31)
    end_date = datetime.datetime.now()
    interval = "days"

    if request.method == "POST":
        form = DateRangeIntervalForm(request.POST)
        if form.is_valid():
            start_date = form.cleaned_data.get("start_date")
            start_date = datetime.datetime.strptime(start_date + " 00:00:00", "%Y-%m-%d %H:%M:%S")
            end_date = form.cleaned_data.get("end_date")
            end_date = datetime.datetime.strptime(end_date + " 23:59:59", "%Y-%m-%d %H:%M:%S")
            interval = form.cleaned_data.get("interval")
    else:
        data = {}
        data["start_date"] = start_date
        data["end_date"] = end_date
        data["interval"] = interval
        form = DateRangeIntervalForm(initial=data)

    dates = []
    if interval == "days":
        daily_stats = (
            CourseDailyStats.objects.filter(course=course, day__gte=start_date, day__lte=end_date)
            .values("day", "type")
            .annotate(total=Sum("total"))
        )

        dates = generate_graph_data(daily_stats, False)

    else:
        monthly_stats = (
            CourseDailyStats.objects.filter(course=course, day__gte=start_date, day__lte=end_date)
            .extra({"month": "month(day)", "year": "year(day)"})
            .values("month", "year", "type")
            .annotate(total=Sum("total"))
            .order_by("year", "month")
        )

        dates = generate_graph_data(monthly_stats, True)

    leaderboard = Points.get_leaderboard(10, course)
    return render_to_response(
        "oppia/course/activity.html",
        {"course": course, "form": form, "data": dates, "leaderboard": leaderboard},
        context_instance=RequestContext(request),
    )
コード例 #6
0
def recent_activity(request, course_id):

    course, response = can_view_course_detail(request, course_id)

    if response is not None:
        return response

    dashboard_accessed.send(sender=None, request=request, data=course)

    start_date = datetime.datetime.now() - datetime.timedelta(days=31)
    end_date = datetime.datetime.now()
    interval = 'days'

    if request.method == 'POST':
        form = DateRangeIntervalForm(request.POST)
        if form.is_valid():
            start_date = form.cleaned_data.get("start_date")
            start_date = datetime.datetime.strptime(start_date + " 00:00:00",
                                                    "%Y-%m-%d %H:%M:%S")
            end_date = form.cleaned_data.get("end_date")
            end_date = datetime.datetime.strptime(end_date + " 23:59:59",
                                                  "%Y-%m-%d %H:%M:%S")
            interval = form.cleaned_data.get("interval")
    else:
        data = {}
        data['start_date'] = start_date
        data['end_date'] = end_date
        data['interval'] = interval
        form = DateRangeIntervalForm(initial=data)

    dates = []
    if interval == 'days':
        daily_stats = CourseDailyStats.objects.filter(course=course, day__gte=start_date, day__lte=end_date)\
                        .values('day','type')\
                        .annotate(total=Sum('total'))

        dates = generate_graph_data(daily_stats, False)

    else:
        monthly_stats = CourseDailyStats.objects.filter(course=course, day__gte=start_date, day__lte=end_date)\
                        .extra({'month':'month(day)', 'year':'year(day)'})\
                        .values('month','year','type')\
                        .annotate(total=Sum('total'))\
                        .order_by('year','month')

        dates = generate_graph_data(monthly_stats, True)

    leaderboard = Points.get_leaderboard(10, course)
    return render_to_response('oppia/course/activity.html', {
        'course': course,
        'form': form,
        'data': dates,
        'leaderboard': leaderboard
    },
                              context_instance=RequestContext(request))
コード例 #7
0
def incomplete_profiles_view(request):
    # check user has report permissions
    if not reporting_access(request.user):
        return HttpResponse('Unauthorized', status=401)
    
    dashboard_accessed.send(sender=None, request=request, data=None)
    
    users = User.objects.filter(userprofile__location=None,is_staff=False)
    return render_to_response('oppia/reports/incomplete-profiles.html',
                              {'users': users,
                               }, 
                              context_instance=RequestContext(request))
コード例 #8
0
def incomplete_profiles_view(request):
    # check user has report permissions
    if not reporting_access(request.user):
        return HttpResponse('Unauthorized', status=401)

    dashboard_accessed.send(sender=None, request=request, data=None)

    users = User.objects.filter(userprofile__location=None, is_staff=False)
    return render_to_response('oppia/reports/incomplete-profiles.html', {
        'users': users,
    },
                              context_instance=RequestContext(request))
コード例 #9
0
def courses_list_view(request):

    if request.is_ajax():
        #if we are requesting via ajax, just show the course list
        ordering, courses = get_paginated_courses(request)
        return render(request, 'oppia/course/courses-paginated-list.html',
                              {'page': courses,
                                  'page_ordering': ordering,
                                  'ajax_url': request.path})
    else:
        courses = can_view_courses_list(request)

        dashboard_accessed.send(sender=None, request=request, data=None)
        return render_courses_list(request, courses)
コード例 #10
0
def courses_list_view(request):

    if request.is_ajax():
        # if we are requesting via ajax, just show the course list
        ordering, courses = get_paginated_courses(request)
        return render_to_response(
            "oppia/course/courses-paginated-list.html",
            {"page": courses, "page_ordering": ordering, "ajax_url": request.path},
            context_instance=RequestContext(request),
        )
    else:
        courses, response = can_view_courses_list(request)
        if response is not None:
            return response

        dashboard_accessed.send(sender=None, request=request, data=None)
        return render_courses_list(request, courses)
コード例 #11
0
def user_activity(request, user_id):
    
    view_user, response = get_user(request, user_id)
    if response is not None:
        return response
    
    dashboard_accessed.send(sender=None, request=request, data=None)
    
    cohort_courses, other_courses, all_courses = get_user_courses(request, view_user) 
    
    courses = []
    for course in all_courses:
        data = {'course': course,
                'no_quizzes_completed': course.get_no_quizzes_completed(course,view_user),
                'pretest_score': course.get_pre_test_score(course,view_user),
                'no_activities_completed': course.get_activities_completed(course,view_user),
                'no_quizzes_completed': course.get_no_quizzes_completed(course,view_user),
                'no_points': course.get_points(course,view_user),
                'no_badges': course.get_badges(course,view_user),}
        courses.append(data)
    
    activity = []
    start_date = timezone.now() - datetime.timedelta(days=31)
    end_date = timezone.now()
    no_days = (end_date-start_date).days + 1
    
    course_ids = list(chain(cohort_courses.values_list('id',flat=True),other_courses.values_list('id',flat=True)))
    trackers = Tracker.objects.filter(course__id__in=course_ids, 
                                      user=view_user, 
                                      tracker_date__gte=start_date,
                                      tracker_date__lte=end_date) \
                                      .extra({'activity_date':"date(tracker_date)"}) \
                                      .values('activity_date') \
                                      .annotate(count=Count('id'))
    for i in range(0,no_days,+1):
        temp = start_date + datetime.timedelta(days=i)
        count = next((dct['count'] for dct in trackers if dct['activity_date'] == temp.date()), 0)
        activity.append([temp.strftime("%d %b %Y"),count])
        
    return render_to_response('oppia/profile/user-scorecard.html',
                              {'view_user': view_user,
                               'courses': courses, 
                               'activity_graph_data': activity }, 
                              context_instance=RequestContext(request))
コード例 #12
0
def courses_list_view(request):

    if request.is_ajax():
        #if we are requesting via ajax, just show the course list
        ordering, courses = get_paginated_courses(request)
        return render_to_response(
            'oppia/course/courses-paginated-list.html',
            {
                'page': courses,
                'page_ordering': ordering,
                'ajax_url': request.path
            },
            context_instance=RequestContext(request),
        )
    else:
        courses, response = can_view_courses_list(request)
        if response is not None:
            return response

        dashboard_accessed.send(sender=None, request=request, data=None)
        return render_courses_list(request, courses)
コード例 #13
0
def courses_list_view(request):
    courses, response = can_view_courses_list(request) 
    if response is not None:
        return response
    
    dashboard_accessed.send(sender=None, request=request, data=None)
           
    tag_list = Tag.objects.all().exclude(coursetag=None).order_by('name')
    courses_list = []
    for course in courses:
        obj = {}
        obj['course'] = course
        access_detail, response = can_view_course_detail(request,course.id)
        if access_detail is not None:
            obj['access_detail'] = True
        else:
            obj['access_detail'] = False
        courses_list.append(obj)
        
    return render_to_response('oppia/course/courses-list.html',
                              {'courses_list': courses_list, 
                               'tag_list': tag_list}, 
                              context_instance=RequestContext(request))
コード例 #14
0
def user_course_activity_view(request, user_id, course_id):

    view_user, response = get_user(request, user_id)
    if response is not None:
        return response

    dashboard_accessed.send(sender=None, request=request, data=None)
    course = can_view_course(request, course_id)

    act_quizzes = Activity.objects.filter(section__course=course,
                                          type=Activity.QUIZ).order_by(
                                              'section__order', 'order')
    quizzes = []
    for aq in act_quizzes:
        quiz = Quiz.objects.get(quizprops__value=aq.digest,
                                quizprops__name="digest")
        attempts = QuizAttempt.objects.filter(
            quiz=quiz, user=view_user).order_by(
                'submitted_date')[:settings.ISCHOOL_MAX_QUIZ_ATTEMPTS]

        max_score = None
        min_score = None
        avg_score = None
        first_score = None
        latest_score = None

        if attempts.count() > 0:
            max_score = 100 * float(
                attempts.aggregate(max=Max('score'))['max']) / float(
                    attempts[0].maxscore)
            min_score = 100 * float(
                attempts.aggregate(min=Min('score'))['min']) / float(
                    attempts[0].maxscore)
            avg_score = 100 * float(
                attempts.aggregate(avg=Avg('score'))['avg']) / float(
                    attempts[0].maxscore)
            first_date = attempts.aggregate(date=Min('attempt_date'))['date']
            recent_date = attempts.aggregate(date=Max('attempt_date'))['date']
            first_score = 100 * float(
                attempts.filter(attempt_date=first_date)[0].score) / float(
                    attempts[0].maxscore)
            latest_score = 100 * float(
                attempts.filter(attempt_date=recent_date)[0].score) / float(
                    attempts[0].maxscore)
        else:
            max_score = None
            min_score = None
            avg_score = None
            first_score = None
            latest_score = None

        quiz = {
            'quiz': aq,
            'no_attempts': attempts.count(),
            'max_score': max_score,
            'min_score': min_score,
            'first_score': first_score,
            'latest_score': latest_score,
            'avg_score': avg_score,
        }
        quizzes.append(quiz)

    activity = []
    start_date = timezone.now() - datetime.timedelta(days=31)
    end_date = timezone.now()
    no_days = (end_date - start_date).days + 1

    trackers = Tracker.objects.filter(course=course,
                                      user=view_user,
                                      tracker_date__gte=start_date,
                                      tracker_date__lte=end_date) \
                                      .extra({'activity_date':"date(tracker_date)"}) \
                                      .values('activity_date') \
                                      .annotate(count=Count('id'))
    for i in range(0, no_days, +1):
        temp = start_date + datetime.timedelta(days=i)
        count = next(
            (dct['count']
             for dct in trackers if dct['activity_date'] == temp.date()), 0)
        activity.append([temp.strftime("%d %b %Y"), count])

    return render_to_response('oppia/profile/user-course-scorecard.html', {
        'view_user': view_user,
        'course': course,
        'quizzes': quizzes,
        'activity_graph_data': activity
    },
                              context_instance=RequestContext(request))
コード例 #15
0
def recent_activity(request, course_id):
    course, response = can_view_course_detail(request, course_id)

    if response is not None:
        return response

    dashboard_accessed.send(sender=None, request=request, data=course)

    start_date = datetime.datetime.now() - datetime.timedelta(days=31)
    end_date = datetime.datetime.now()
    interval = 'days'

    if request.method == 'POST':
        form = DateRangeIntervalForm(request.POST)
        if form.is_valid():
            start_date = form.cleaned_data.get("start_date")
            start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
            end_date = form.cleaned_data.get("end_date")
            end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
            interval = form.cleaned_data.get("interval")
    else:
        data = {}
        data['start_date'] = start_date
        data['end_date'] = end_date
        data['interval'] = interval
        form = DateRangeIntervalForm(initial=data)

    dates = []
    if interval == 'days':
        no_days = (end_date - start_date).days + 1

        for i in range(0, no_days, +1):
            temp = start_date + datetime.timedelta(days=i)
            day = temp.strftime("%d")
            month = temp.strftime("%m")
            year = temp.strftime("%Y")
            count_objs = Tracker.objects.filter(
                course=course,
                tracker_date__day=day,
                tracker_date__month=month,
                tracker_date__year=year).values('type').annotate(
                    total=Count('type'))
            count_activity = {
                'page': 0,
                'quiz': 0,
                'media': 0,
                'resource': 0,
                'monitor': 0,
                'total': 0
            }
            for co in count_objs:
                if co['type'] in count_activity:
                    count_activity[
                        co['type']] = count_activity[co['type']] + co['total']
                    count_activity[
                        'total'] = count_activity['total'] + co['total']
                else:
                    count_activity[co['type']] = 0
                    count_activity[
                        co['type']] = count_activity[co['type']] + co['total']
                    count_activity[
                        'total'] = count_activity['total'] + co['total']

            dates.append([temp.strftime("%d %b %y"), count_activity])
    else:
        delta = relativedelta(months=+1)
        no_months = 0
        tmp_date = start_date
        while tmp_date <= end_date:
            print tmp_date
            tmp_date += delta
            no_months += 1

        for i in range(0, no_months, +1):
            temp = start_date + relativedelta(months=+i)
            month = temp.strftime("%m")
            year = temp.strftime("%Y")
            count_objs = Tracker.objects.filter(
                course=course,
                tracker_date__month=month,
                tracker_date__year=year).values('type').annotate(
                    total=Count('type'))
            count_activity = {
                'page': 0,
                'quiz': 0,
                'media': 0,
                'resource': 0,
                'monitor': 0,
                'total': 0
            }
            for co in count_objs:
                if co['type'] in count_activity:
                    count_activity[
                        co['type']] = count_activity[co['type']] + co['total']
                    count_activity[
                        'total'] = count_activity['total'] + co['total']
                else:
                    count_activity[co['type']] = 0
                    count_activity[
                        co['type']] = count_activity[co['type']] + co['total']
                    count_activity[
                        'total'] = count_activity['total'] + co['total']

            dates.append([temp.strftime("%b %y"), count_activity])

    leaderboard = Points.get_leaderboard(10, course)
    return render_to_response('oppia/course/activity.html', {
        'course': course,
        'form': form,
        'data': dates,
        'leaderboard': leaderboard
    },
                              context_instance=RequestContext(request))
コード例 #16
0
def home_view(request):

    activity = []
    leaderboard = None

    if request.user.is_authenticated():
        # create profile if none exists (historical for very old users)
        try:
            up = request.user.userprofile
        except UserProfile.DoesNotExist:
            up = UserProfile()
            up.user = request.user
            up.save()

        dashboard_accessed.send(sender=None, request=request, data=None)

        # if user is student redirect to their scorecard
        if up.is_student_only():
            return HttpResponseRedirect(reverse("profile_user_activity", args=[request.user.id]))

        # is user is teacher redirect to teacher home
        if up.is_teacher_only():
            return HttpResponseRedirect(reverse("oppia_teacher_home"))

        start_date = timezone.now() - datetime.timedelta(days=31)
        end_date = timezone.now()
        interval = "days"
        if request.method == "POST":
            form = DateRangeIntervalForm(request.POST)
            if form.is_valid():
                start_date = form.cleaned_data.get("start_date")
                start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
                end_date = form.cleaned_data.get("end_date")
                end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
                interval = form.cleaned_data.get("interval")
        else:
            data = {}
            data["start_date"] = start_date
            data["end_date"] = end_date
            data["interval"] = interval
            form = DateRangeIntervalForm(initial=data)

        if interval == "days":
            no_days = (end_date - start_date).days + 1
            tracker_stats = (
                CourseDailyStats.objects.filter(day__gte=start_date, day__lte=end_date)
                .values("day")
                .annotate(count=Sum("total"))
            )

            for i in range(0, no_days, +1):
                temp = start_date + datetime.timedelta(days=i)
                count = next((dct["count"] for dct in tracker_stats if dct["day"] == temp.date()), 0)
                activity.append([temp.strftime("%d %b %Y"), count])
        else:
            delta = relativedelta(months=+1)

            no_months = 0
            tmp_date = start_date
            while tmp_date <= end_date:
                print tmp_date
                tmp_date += delta
                no_months += 1

            for i in range(0, no_months, +1):
                temp = start_date + relativedelta(months=+i)
                month = temp.strftime("%m")
                year = temp.strftime("%Y")
                count = (
                    CourseDailyStats.objects.filter(day__month=month, day__year=year)
                    .aggregate(total=Sum("total"))
                    .get("total", 0)
                )
                activity.append([temp.strftime("%b %Y"), 0 if count is None else count])

            print activity

        leaderboard = Points.get_leaderboard(10)

    else:
        form = None

    return render_to_response(
        "oppia/home.html",
        {"form": form, "activity_graph_data": activity, "leaderboard": leaderboard},
        context_instance=RequestContext(request),
    )
コード例 #17
0
def recent_activity(request,course_id):
    course, response = can_view_course_detail(request, course_id)
    
    if response is not None:
        return response
    
    dashboard_accessed.send(sender=None, request=request, data=course)
    
    start_date = datetime.datetime.now() - datetime.timedelta(days=31)
    end_date = datetime.datetime.now()
    interval = 'days'
    
    if request.method == 'POST':
        form = DateRangeIntervalForm(request.POST)
        if form.is_valid():
            start_date = form.cleaned_data.get("start_date")  
            start_date = datetime.datetime.strptime(start_date,"%Y-%m-%d")
            end_date = form.cleaned_data.get("end_date")
            end_date = datetime.datetime.strptime(end_date,"%Y-%m-%d") 
            interval =  form.cleaned_data.get("interval")               
    else:
        data = {}
        data['start_date'] = start_date
        data['end_date'] = end_date
        data['interval'] = interval
        form = DateRangeIntervalForm(initial=data)
    
    dates = []
    if interval == 'days':
        no_days = (end_date-start_date).days + 1
        
        for i in range(0,no_days,+1):
            temp = start_date + datetime.timedelta(days=i)
            day = temp.strftime("%d")
            month = temp.strftime("%m")
            year = temp.strftime("%Y")
            count_objs = Tracker.objects.filter(course=course,tracker_date__day=day,tracker_date__month=month,tracker_date__year=year).values('type').annotate(total=Count('type'))
            count_activity = {'page':0, 'quiz':0, 'media':0, 'resource':0, 'monitor': 0, 'total':0}
            for co in count_objs:
                if co['type'] in count_activity:
                    count_activity[co['type']] = count_activity[co['type']] + co['total']
                    count_activity['total'] = count_activity['total'] + co['total']
                else:
                    count_activity[co['type']] = 0
                    count_activity[co['type']] = count_activity[co['type']] + co['total']
                    count_activity['total'] = count_activity['total'] + co['total']
            
            dates.append([temp.strftime("%d %b %y"),count_activity])
    else:
        delta = relativedelta(months=+1)  
        no_months = 0
        tmp_date = start_date
        while tmp_date <= end_date:
            print tmp_date
            tmp_date += delta
            no_months += 1
            
        for i in range(0,no_months,+1):
            temp = start_date + relativedelta(months=+i)
            month = temp.strftime("%m")
            year = temp.strftime("%Y")
            count_objs = Tracker.objects.filter(course=course,tracker_date__month=month,tracker_date__year=year).values('type').annotate(total=Count('type'))
            count_activity = {'page':0, 'quiz':0, 'media':0, 'resource':0, 'monitor': 0, 'total':0}
            for co in count_objs:
                if co['type'] in count_activity:
                    count_activity[co['type']] = count_activity[co['type']] + co['total']
                    count_activity['total'] = count_activity['total'] + co['total']
                else:
                    count_activity[co['type']] = 0
                    count_activity[co['type']] = count_activity[co['type']] + co['total']
                    count_activity['total'] = count_activity['total'] + co['total']
            
            dates.append([temp.strftime("%b %y"),count_activity])
        
        
    leaderboard = Points.get_leaderboard(10, course)
    return render_to_response('oppia/course/activity.html',
                              {'course': course,
                               'form': form,
                                'data':dates, 
                                'leaderboard':leaderboard}, 
                              context_instance=RequestContext(request))
コード例 #18
0
def user_course_activity_view(request, user_id, course_id):

    view_user, response = get_user(request, user_id)
    if response is not None:
        return response

    dashboard_accessed.send(sender=None, request=request, data=None)
    course = can_view_course(request, course_id)

    act_quizzes = Activity.objects.filter(section__course=course,
                                          type=Activity.QUIZ).order_by(
                                              'section__order', 'order')

    quizzes_attempted = 0
    quizzes_passed = 0
    course_pretest = None

    quizzes = []
    for aq in act_quizzes:
        try:
            quiz = Quiz.objects.get(quizprops__value=aq.digest,
                                    quizprops__name="digest")
        except Quiz.DoesNotExist:
            quiz = None

        attempts = QuizAttempt.objects.filter(quiz=quiz, user=view_user)
        num_attempts = attempts.count()
        passed = False
        if num_attempts > 0:

            quiz_maxscore = float(attempts[0].maxscore)
            attemps_stats = attempts.aggregate(max=Max('score'),
                                               min=Min('score'),
                                               avg=Avg('score'))
            max_score = 100 * float(attemps_stats['max']) / quiz_maxscore
            min_score = 100 * float(attemps_stats['min']) / quiz_maxscore
            avg_score = 100 * float(attemps_stats['avg']) / quiz_maxscore
            first_date = attempts.aggregate(date=Min('attempt_date'))['date']
            recent_date = attempts.aggregate(date=Max('attempt_date'))['date']
            first_score = 100 * float(
                attempts.filter(
                    attempt_date=first_date)[0].score) / quiz_maxscore
            latest_score = 100 * float(
                attempts.filter(
                    attempt_date=recent_date)[0].score) / quiz_maxscore

            passed = max_score is not None and max_score > 75
            if aq.section.order == 0:
                course_pretest = first_score
            else:
                quizzes_attempted += 1
                quizzes_passed = (quizzes_passed +
                                  1) if passed else quizzes_passed

        else:
            max_score = None
            min_score = None
            avg_score = None
            first_score = None
            latest_score = None

        quiz = {
            'quiz': aq,
            'quiz_order': aq.order,
            'no_attempts': num_attempts,
            'max_score': max_score,
            'min_score': min_score,
            'first_score': first_score,
            'latest_score': latest_score,
            'avg_score': avg_score,
            'passed': passed
        }
        quizzes.append(quiz)

    activities_completed = course.get_activities_completed(course, view_user)
    activities_total = course.get_no_activities()
    activities_percent = (activities_completed * 100) / activities_total

    activity = []
    start_date = timezone.now() - datetime.timedelta(days=31)
    end_date = timezone.now()
    no_days = (end_date - start_date).days + 1

    trackers = Tracker.objects.filter(course=course,
                                      user=view_user,
                                      tracker_date__gte=start_date,
                                      tracker_date__lte=end_date) \
                                      .extra({'activity_date':"date(tracker_date)"}) \
                                      .values('activity_date') \
                                      .annotate(count=Count('id'))
    for i in range(0, no_days, +1):
        temp = start_date + datetime.timedelta(days=i)
        count = next(
            (dct['count']
             for dct in trackers if dct['activity_date'] == temp.date()), 0)
        activity.append([temp.strftime("%d %b %Y"), count])

    order_options = [
        'quiz_order', 'no_attempts', 'max_score', 'min_score', 'first_score',
        'latest_score', 'avg_score'
    ]
    default_order = 'quiz_order'
    ordering = request.GET.get('order_by', default_order)
    inverse_order = ordering.startswith('-')
    if inverse_order:
        ordering = ordering[1:]
    if ordering not in order_options:
        ordering = default_order
        inverse_order = False

    quizzes.sort(key=operator.itemgetter(ordering), reverse=inverse_order)

    return render_to_response(
        'oppia/profile/user-course-scorecard.html', {
            'view_user': view_user,
            'course': course,
            'quizzes': quizzes,
            'quizzes_passed': quizzes_passed,
            'quizzes_attempted': quizzes_attempted,
            'pretest_score': course_pretest,
            'activities_completed': activities_completed,
            'activities_total': activities_total,
            'activities_percent': activities_percent,
            'page_ordering': ('-' if inverse_order else '') + ordering,
            'activity_graph_data': activity
        },
        context_instance=RequestContext(request))
コード例 #19
0
def user_activity(request, user_id):

    view_user, response = get_user(request, user_id)
    if response is not None:
        return response

    dashboard_accessed.send(sender=None, request=request, data=None)

    cohort_courses, other_courses, all_courses = get_user_courses(
        request, view_user)

    courses = []
    for course in all_courses:
        course_stats = UserCourseSummary.objects.filter(user=view_user,
                                                        course=course)[0]
        data = {
            'course': course,
            'no_quizzes_completed': course_stats.quizzes_passed,
            'pretest_score': course_stats.pretest_score,
            'no_activities_completed': course_stats.completed_activities,
            'no_media_viewed': course_stats.media_viewed,
            'no_points': course_stats.points,
            'no_badges': course_stats.badges_achieved,
        }
        courses.append(data)

    order_options = [
        'course', 'no_quizzes_completed', 'pretest_score',
        'no_activities_completed', 'no_points', 'no_badges', 'no_media_viewed'
    ]
    default_order = 'course'

    ordering = request.GET.get('order_by', default_order)
    inverse_order = ordering.startswith('-')
    if inverse_order:
        ordering = ordering[1:]

    if ordering not in order_options:
        ordering = default_order
        inverse_order = False

    courses.sort(key=operator.itemgetter(ordering), reverse=inverse_order)

    activity = []
    start_date = timezone.now() - datetime.timedelta(days=31)
    end_date = timezone.now()
    no_days = (end_date - start_date).days + 1

    course_ids = list(
        chain(cohort_courses.values_list('id', flat=True),
              other_courses.values_list('id', flat=True)))
    trackers = Tracker.objects.filter(course__id__in=course_ids,
                                      user=view_user,
                                      tracker_date__gte=start_date,
                                      tracker_date__lte=end_date) \
                                      .extra({'activity_date':"date(tracker_date)"}) \
                                      .values('activity_date') \
                                      .annotate(count=Count('id'))
    for i in range(0, no_days, +1):
        temp = start_date + datetime.timedelta(days=i)
        count = next(
            (dct['count']
             for dct in trackers if dct['activity_date'] == temp.date()), 0)
        activity.append([temp.strftime("%d %b %Y"), count])

    return render_to_response(
        'oppia/profile/user-scorecard.html', {
            'view_user': view_user,
            'courses': courses,
            'page_ordering': ('-' if inverse_order else '') + ordering,
            'activity_graph_data': activity
        },
        context_instance=RequestContext(request))
コード例 #20
0
def pass_rate_view_by_course(request):

    start_date = timezone.now() - datetime.timedelta(days=31)
    end_date = timezone.now()

    if request.method == 'POST':
        form = ProvinceDateDiffForm(request.POST)
        form.fields['provinces'].choices = [
            (p.id, p.name) for p in reporting_province_access(request.user)
        ]

        dashboard_accessed.send(sender=None,
                                request=request,
                                data=json.dumps(request.POST))

        if form.is_valid():
            start_date = form.cleaned_data.get("start_date")
            start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
            end_date = form.cleaned_data.get("end_date")
            # add one extra day so works out on (eg) before 2016-05-04 00:00:00 rather than 2016-05-03 00:00:00 when 2016-05-03 is the selected date
            end_date = datetime.datetime.strptime(
                end_date, "%Y-%m-%d") + relativedelta(days=1)
            province = Province.objects.get(
                pk=form.cleaned_data.get("provinces"))

            courses = Course.objects.filter(is_draft=False, is_archived=False)
            districts = reporting_district_access(
                user=request.user, province=province).order_by('name')
            results = []

            for course in courses:
                result = {}
                result['course'] = course
                result['districts'] = []

                for district in districts:
                    district_results = {}
                    district_results['district'] = district
                    district_results['facilities'] = []
                    district_results['passed'] = 0
                    district_results['failed'] = 0
                    district_results['total'] = 0

                    for i in range(1,
                                   int(settings.ISCHOOL_MAX_QUIZ_ATTEMPTS) +
                                   1):
                        district_results['passedattempt' + str(i)] = 0

                    facilities = reporting_facility_access(
                        user=request.user, district=district).order_by('name')

                    for facility in facilities:
                        facility_results = {}
                        facility_results['facility'] = facility
                        for i in range(
                                1,
                                int(settings.ISCHOOL_MAX_QUIZ_ATTEMPTS) + 1):
                            facility_results['passedattempt' + str(i)] = 0

                        # get the quizzes for the course
                        quiz_acts = Activity.objects.filter(
                            type=Activity.QUIZ,
                            section__course=course).exclude(
                                section__order=0).values_list('digest',
                                                              flat=True)
                        trackers = Tracker.objects.filter(
                            submitted_date__gte=start_date,
                            submitted_date__lte=end_date,
                            digest__in=quiz_acts,
                            user__userprofile__location=facility)

                        # get the total no people who passed/failed the quiz during this time
                        users_passed = []
                        users_failed = []
                        user_passed_attempts = {}
                        for i in range(
                                1,
                                int(settings.ISCHOOL_MAX_QUIZ_ATTEMPTS) + 1):
                            user_passed_attempts['passedattempt' + str(i)] = []

                        for counter, t in enumerate(trackers):
                            # check it's not more than the users 3rd attempt
                            no_previous_attempts = Tracker.objects.filter(
                                submitted_date__lt=t.submitted_date,
                                user=t.user,
                                digest=t.digest).count()
                            if no_previous_attempts > (
                                    settings.ISCHOOL_MAX_QUIZ_ATTEMPTS - 1):
                                continue

                            if t.completed == True:
                                if t.user not in users_passed:
                                    users_passed.append(t.user)
                                    user_passed_attempts['passedattempt' +
                                                         str(counter +
                                                             1)].append(t.user)
                            else:
                                if t.user not in users_failed:
                                    users_failed.append(t.user)

                        users_failed = list(
                            set(users_failed) - set(users_passed))

                        facility_results['passed'] = users_passed
                        facility_results['failed'] = users_failed
                        facility_results['total'] = len(users_failed) + len(
                            users_passed)

                        for i in range(
                                1,
                                int(settings.ISCHOOL_MAX_QUIZ_ATTEMPTS) + 1):
                            facility_results['passedattempt' + str(i)] = set(
                                user_passed_attempts['passedattempt' + str(i)])

                        district_results['passed'] += len(users_passed)
                        district_results['failed'] += len(users_failed)
                        district_results['total'] += len(users_failed) + len(
                            users_passed)

                        for i in range(
                                1,
                                int(settings.ISCHOOL_MAX_QUIZ_ATTEMPTS) + 1):
                            district_results['passedattempt' + str(i)] += len(
                                facility_results['passedattempt' + str(i)])

                        district_results['facilities'].append(facility_results)

                    result['districts'].append(district_results)
                results.append(result)

                # Create the totals for the course (all districts)
                course_summary = {}
                course_summary['passed'] = 0
                course_summary['failed'] = 0
                course_summary['total'] = 0

                for i in range(1, int(settings.ISCHOOL_MAX_QUIZ_ATTEMPTS) + 1):
                    course_summary['passedattempt' + str(i)] = 0

                for d in result['districts']:
                    course_summary['passed'] += d['passed']
                    course_summary['failed'] += d['failed']
                    course_summary['total'] += d['total']
                    for i in range(1,
                                   int(settings.ISCHOOL_MAX_QUIZ_ATTEMPTS) +
                                   1):
                        course_summary['passedattempt' +
                                       str(i)] += d['passedattempt' + str(i)]

                result['course_summary'] = course_summary

            return render_to_response('oppia/reports/pass-rate-by-course.html',
                                      {
                                          'results': results,
                                          'form': form,
                                          'start_date': start_date,
                                          'end_date': end_date,
                                          'province': province,
                                      },
                                      context_instance=RequestContext(request))
        return render_to_response('oppia/reports/pass-rate-by-course.html', {
            'form': form,
            'start_date': start_date,
            'end_date': end_date,
        },
                                  context_instance=RequestContext(request))
    else:
        data = {}
        data['start_date'] = start_date
        data['end_date'] = end_date
        form = ProvinceDateDiffForm(initial=data)
        form.fields['provinces'].choices = [
            (p.id, p.name) for p in reporting_province_access(request.user)
        ]

        dashboard_accessed.send(sender=None, request=request, data=None)

        return render_to_response('oppia/reports/pass-rate-by-course.html', {
            'form': form,
            'start_date': start_date,
            'end_date': end_date,
        },
                                  context_instance=RequestContext(request))
コード例 #21
0
ファイル: views.py プロジェクト: QCInvestments/django-oppia
def user_course_activity_view(request, user_id, course_id):

    view_user, response = get_user(request, user_id)
    if response is not None:
        return response

    dashboard_accessed.send(sender=None, request=request, data=None)
    course = can_view_course(request, course_id)

    act_quizzes = Activity.objects.filter(section__course=course,type=Activity.QUIZ).order_by('section__order','order')

    quizzes_attempted = 0
    quizzes_passed = 0
    course_pretest = None

    quizzes = []
    for aq in act_quizzes:
        try:
            quiz = Quiz.objects.get(quizprops__value=aq.digest, quizprops__name="digest")
        except Quiz.DoesNotExist:
            quiz = None


        attempts = QuizAttempt.objects.filter(quiz=quiz, user=view_user)
        num_attempts = attempts.count()
        passed = False
        if num_attempts > 0:

            quiz_maxscore = float(attempts[0].maxscore)
            attemps_stats = attempts.aggregate(max=Max('score'), min=Min('score'), avg=Avg('score'))
            max_score = 100*float(attemps_stats['max']) / quiz_maxscore
            min_score = 100*float(attemps_stats['min']) / quiz_maxscore
            avg_score = 100*float(attemps_stats['avg']) / quiz_maxscore
            first_date = attempts.aggregate(date=Min('attempt_date'))['date']
            recent_date = attempts.aggregate(date=Max('attempt_date'))['date']
            first_score = 100*float(attempts.filter(attempt_date = first_date)[0].score) / quiz_maxscore
            latest_score = 100*float(attempts.filter(attempt_date = recent_date)[0].score) / quiz_maxscore

            passed = max_score is not None and max_score > 75
            if aq.section.order == 0:
                course_pretest = first_score
            else:
                quizzes_attempted += 1
                quizzes_passed = (quizzes_passed + 1) if passed else quizzes_passed

        else:
            max_score = None
            min_score = None
            avg_score = None
            first_score = None
            latest_score = None

        quiz = {'quiz': aq,
                'quiz_order': aq.order,
                'no_attempts': num_attempts,
                'max_score': max_score,
                'min_score': min_score,
                'first_score': first_score,
                'latest_score': latest_score,
                'avg_score': avg_score,
                'passed': passed
                 }
        quizzes.append(quiz)

    activities_completed = course.get_activities_completed(course,view_user)
    activities_total = course.get_no_activities()
    activities_percent = (activities_completed * 100) / activities_total

    activity = []
    start_date = timezone.now() - datetime.timedelta(days=31)
    end_date = timezone.now()
    no_days = (end_date-start_date).days + 1

    trackers = Tracker.objects.filter(course=course,
                                      user=view_user,
                                      tracker_date__gte=start_date,
                                      tracker_date__lte=end_date) \
                                      .extra({'activity_date':"date(tracker_date)"}) \
                                      .values('activity_date') \
                                      .annotate(count=Count('id'))
    for i in range(0,no_days,+1):
        temp = start_date + datetime.timedelta(days=i)
        count = next((dct['count'] for dct in trackers if dct['activity_date'] == temp.date()), 0)
        activity.append([temp.strftime("%d %b %Y"),count])

    order_options = ['quiz_order', 'no_attempts', 'max_score', 'min_score',
                     'first_score', 'latest_score', 'avg_score']
    default_order = 'quiz_order'
    ordering = request.GET.get('order_by', default_order)
    inverse_order = ordering.startswith('-')
    if inverse_order:
        ordering = ordering[1:]
    if ordering not in order_options:
        ordering = default_order
        inverse_order = False

    quizzes.sort(key=operator.itemgetter(ordering), reverse=inverse_order)

    return render_to_response('oppia/profile/user-course-scorecard.html',
                              {'view_user': view_user,
                               'course': course,
                               'quizzes': quizzes,
                               'quizzes_passed':quizzes_passed,
                               'quizzes_attempted':quizzes_attempted,
                               'pretest_score': course_pretest,
                               'activities_completed': activities_completed,
                               'activities_total': activities_total,
                               'activities_percent': activities_percent,
                               'page_ordering': ('-' if inverse_order else '') + ordering,
                               'activity_graph_data': activity },
                              context_instance=RequestContext(request))
コード例 #22
0
ファイル: views.py プロジェクト: QCInvestments/django-oppia
def user_activity(request, user_id):

    view_user, response = get_user(request, user_id)
    if response is not None:
        return response

    dashboard_accessed.send(sender=None, request=request, data=None)

    cohort_courses, other_courses, all_courses = get_user_courses(request, view_user)

    courses = []
    for course in all_courses:
        course_stats = UserCourseSummary.objects.filter(user=view_user, course=course)[0]
        data = {'course': course,
                'no_quizzes_completed': course_stats.quizzes_passed ,
                'pretest_score': course_stats.pretest_score,
                'no_activities_completed': course_stats.completed_activities,
                'no_media_viewed': course_stats.media_viewed,
                'no_points': course_stats.points,
                'no_badges': course_stats.badges_achieved,}
        courses.append(data)

    order_options = ['course', 'no_quizzes_completed', 'pretest_score',
                     'no_activities_completed','no_points', 'no_badges', 'no_media_viewed']
    default_order = 'course'

    ordering = request.GET.get('order_by', default_order)
    inverse_order = ordering.startswith('-')
    if inverse_order:
        ordering = ordering[1:]

    if ordering not in order_options:
        ordering = default_order
        inverse_order = False

    courses.sort(key=operator.itemgetter(ordering), reverse=inverse_order)

    activity = []
    start_date = timezone.now() - datetime.timedelta(days=31)
    end_date = timezone.now()
    no_days = (end_date-start_date).days + 1

    course_ids = list(chain(cohort_courses.values_list('id',flat=True),other_courses.values_list('id',flat=True)))
    trackers = Tracker.objects.filter(course__id__in=course_ids,
                                      user=view_user,
                                      tracker_date__gte=start_date,
                                      tracker_date__lte=end_date) \
                                      .extra({'activity_date':"date(tracker_date)"}) \
                                      .values('activity_date') \
                                      .annotate(count=Count('id'))
    for i in range(0,no_days,+1):
        temp = start_date + datetime.timedelta(days=i)
        count = next((dct['count'] for dct in trackers if dct['activity_date'] == temp.date()), 0)
        activity.append([temp.strftime("%d %b %Y"),count])

    return render_to_response('oppia/profile/user-scorecard.html',
                              {'view_user': view_user,
                               'courses': courses,
                               'page_ordering': ('-' if inverse_order else '') + ordering,
                               'activity_graph_data': activity },
                              context_instance=RequestContext(request))
コード例 #23
0
def home_view(request):
    activity = []
    if request.user.is_authenticated():
        # create profile if none exists (historical for very old users)
        try:
            up = request.user.userprofile
        except UserProfile.DoesNotExist:
            up = UserProfile()
            up.user= request.user
            up.save()
        
        dashboard_accessed.send(sender=None, request=request, data=None)
        
        # if user is student redirect to their scorecard
        if up.is_student_only():
            return HttpResponseRedirect(reverse('profile_user_activity', args=[request.user.id]))
        
        # is user is teacher redirect to teacher home
        if up.is_teacher_only():
            return HttpResponseRedirect(reverse('oppia_teacher_home'))
        
        start_date = timezone.now() - datetime.timedelta(days=31)
        end_date = timezone.now()
        interval = 'days'
        if request.method == 'POST':
            form = DateRangeIntervalForm(request.POST)
            if form.is_valid():
                start_date = form.cleaned_data.get("start_date")  
                start_date = datetime.datetime.strptime(start_date,"%Y-%m-%d")
                end_date = form.cleaned_data.get("end_date")
                end_date = datetime.datetime.strptime(end_date,"%Y-%m-%d")   
                interval =  form.cleaned_data.get("interval")          
        else:
            data = {}
            data['start_date'] = start_date
            data['end_date'] = end_date
            data['interval'] = interval
            form = DateRangeIntervalForm(initial=data)
        
        if interval == 'days':
            no_days = (end_date-start_date).days + 1
            trackers = Tracker.objects.filter(course__isnull=False, 
                                              course__is_draft=False, 
                                              user__is_staff=False, 
                                              course__is_archived=False,
                                              tracker_date__gte=start_date,
                                              tracker_date__lte=end_date).extra({'activity_date':"date(tracker_date)"}).values('activity_date').annotate(count=Count('id'))
            for i in range(0,no_days,+1):
                temp = start_date + datetime.timedelta(days=i)
                count = next((dct['count'] for dct in trackers if dct['activity_date'] == temp.date()), 0)
                activity.append([temp.strftime("%d %b %Y"),count])
        else:
            delta = relativedelta(months=+1)
            
            no_months = 0
            tmp_date = start_date
            while tmp_date <= end_date:
                print tmp_date
                tmp_date += delta
                no_months += 1
                
            for i in range(0,no_months,+1):
                temp = start_date + relativedelta(months=+i)
                month = temp.strftime("%m")
                year = temp.strftime("%Y")
                count = Tracker.objects.filter(course__isnull=False,
                                               course__is_draft=False,
                                               user__is_staff=False,
                                               course__is_archived=False,
                                               tracker_date__month=month,
                                               tracker_date__year=year).count()
                activity.append([temp.strftime("%b %Y"),count])
    else:
        form = None
    leaderboard = Points.get_leaderboard(10)
    return render_to_response('oppia/home.html',
                              {'form': form,
                               'activity_graph_data': activity, 
                               'leaderboard': leaderboard}, 
                              context_instance=RequestContext(request))
コード例 #24
0
def home_view(request):

    activity = []
    leaderboard = None

    if request.user.is_authenticated:
        # create profile if none exists (historical for very old users)
        try:
            up = request.user.userprofile
        except UserProfile.DoesNotExist:
            up = UserProfile()
            up.user = request.user
            up.save()

        dashboard_accessed.send(sender=None, request=request, data=None)

        # if user is student redirect to their scorecard
        if up.is_student_only():
            return HttpResponseRedirect(reverse('profile_user_activity', args=[request.user.id]))

        # is user is teacher redirect to teacher home
        if up.is_teacher_only():
            return HttpResponseRedirect(reverse('oppia_teacher_home'))

        start_date = timezone.now() - datetime.timedelta(days=31)
        end_date = timezone.now()
        interval = 'days'
        if request.method == 'POST':
            form = DateRangeIntervalForm(request.POST)
            if form.is_valid():
                start_date = form.cleaned_data.get("start_date")
                start_date = datetime.datetime.strptime(start_date, "%Y-%m-%d")
                end_date = form.cleaned_data.get("end_date")
                end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
                interval = form.cleaned_data.get("interval")
        else:
            data = {}
            data['start_date'] = start_date
            data['end_date'] = end_date
            data['interval'] = interval
            form = DateRangeIntervalForm(initial=data)

        if interval == 'days':
            no_days = (end_date - start_date).days + 1
            tracker_stats = CourseDailyStats.objects.filter(day__gte=start_date, day__lte=end_date).values('day').annotate(count=Sum('total'))

            for i in range(0, no_days, +1):
                temp = start_date + datetime.timedelta(days=i)
                count = next((dct['count'] for dct in tracker_stats if dct['day'] == temp.date()), 0)
                activity.append([temp.strftime("%d %b %Y"), count])
        else:
            delta = relativedelta(months=+1)

            no_months = 0
            tmp_date = start_date
            while tmp_date <= end_date:
                tmp_date += delta
                no_months += 1

            for i in range(0, no_months, +1):
                temp = start_date + relativedelta(months=+i)
                month = temp.strftime("%m")
                year = temp.strftime("%Y")
                count = CourseDailyStats.objects.filter(day__month=month, day__year=year).aggregate(total=Sum('total')).get('total', 0)
                activity.append([temp.strftime("%b %Y"), 0 if count is None else count])

        leaderboard = Points.get_leaderboard(10)

    else:
        form = None

    return render(request, 'oppia/home.html',
                              {'form': form,
                               'activity_graph_data': activity,
                               'leaderboard': leaderboard})
コード例 #25
0
def user_course_activity_view(request, user_id, course_id):

    view_user, response = get_user(request, user_id)
    if response is not None:
        return response

    dashboard_accessed.send(sender=None, request=request, data=None)
    course = can_view_course(request, course_id)

    act_quizzes = Activity.objects.filter(section__course=course,type=Activity.QUIZ).order_by('section__order','order')
    quizzes = []
    for aq in act_quizzes:
        quiz = Quiz.objects.get(quizprops__value=aq.digest, quizprops__name="digest")
        attempts = QuizAttempt.objects.filter(quiz=quiz, user=view_user).order_by('submitted_date')[:settings.ISCHOOL_MAX_QUIZ_ATTEMPTS]
        
        max_score = None
        min_score = None
        avg_score = None
        first_score = None
        latest_score = None
        
        if attempts.count() > 0:
            max_score = 100*float(attempts.aggregate(max=Max('score'))['max']) / float(attempts[0].maxscore)
            min_score = 100*float(attempts.aggregate(min=Min('score'))['min']) / float(attempts[0].maxscore)
            avg_score = 100*float(attempts.aggregate(avg=Avg('score'))['avg']) / float(attempts[0].maxscore)
            first_date = attempts.aggregate(date=Min('attempt_date'))['date']
            recent_date = attempts.aggregate(date=Max('attempt_date'))['date']
            first_score = 100*float(attempts.filter(attempt_date = first_date)[0].score) / float(attempts[0].maxscore)
            latest_score = 100*float(attempts.filter(attempt_date = recent_date)[0].score) / float(attempts[0].maxscore)
        else:
            max_score = None
            min_score = None
            avg_score = None
            first_score = None
            latest_score = None

        quiz = {'quiz': aq,
                'no_attempts': attempts.count(),
                'max_score': max_score,
                'min_score': min_score,
                'first_score': first_score,
                'latest_score': latest_score,
                'avg_score': avg_score,
                 }
        quizzes.append(quiz);

    activity = []
    start_date = timezone.now() - datetime.timedelta(days=31)
    end_date = timezone.now()
    no_days = (end_date-start_date).days + 1

    trackers = Tracker.objects.filter(course=course,
                                      user=view_user,
                                      tracker_date__gte=start_date,
                                      tracker_date__lte=end_date) \
                                      .extra({'activity_date':"date(tracker_date)"}) \
                                      .values('activity_date') \
                                      .annotate(count=Count('id'))
    for i in range(0,no_days,+1):
        temp = start_date + datetime.timedelta(days=i)
        count = next((dct['count'] for dct in trackers if dct['activity_date'] == temp.date()), 0)
        activity.append([temp.strftime("%d %b %Y"),count])

    return render_to_response('oppia/profile/user-course-scorecard.html',
                              {'view_user': view_user,
                               'course': course,
                               'quizzes': quizzes,
                               'activity_graph_data': activity },
                              context_instance=RequestContext(request))
コード例 #26
0
def pass_rate_view_by_course(request):
    
    start_date = timezone.now() - datetime.timedelta(days=31)
    end_date = timezone.now()
    
    if request.method == 'POST':
        form = ProvinceDateDiffForm(request.POST)        
        form.fields['provinces'].choices = [(p.id,p.name) for p in reporting_province_access(request.user)]
        
        dashboard_accessed.send(sender=None, request=request, data=json.dumps(request.POST))
        
        if form.is_valid():
            start_date = form.cleaned_data.get("start_date")  
            start_date = datetime.datetime.strptime(start_date,"%Y-%m-%d")
            end_date = form.cleaned_data.get("end_date")
            # add one extra day so works out on (eg) before 2016-05-04 00:00:00 rather than 2016-05-03 00:00:00 when 2016-05-03 is the selected date
            end_date = datetime.datetime.strptime(end_date,"%Y-%m-%d") + relativedelta(days=1) 
            province = Province.objects.get(pk=form.cleaned_data.get("provinces"))
            
            courses = Course.objects.filter(is_draft=False,is_archived=False)
            districts = reporting_district_access(user=request.user,province=province).order_by('name')
            results = []
            
            for course in courses:
                result = {}
                result['course'] = course
                result['districts'] = []
                
                for district in districts:
                    district_results = {}
                    district_results['district'] = district
                    district_results['facilities'] = []
                    district_results['passed'] = 0
                    district_results['failed'] = 0
                    district_results['total'] = 0
                    
                    for i in range(1,int(settings.ISCHOOL_MAX_QUIZ_ATTEMPTS)+1):
                        district_results['passedattempt'+str(i)] = 0
                    
                    facilities = reporting_facility_access(user=request.user, district=district).order_by('name')
                    
                    for facility in facilities:
                        facility_results = {}
                        facility_results['facility'] = facility
                        for i in range(1,int(settings.ISCHOOL_MAX_QUIZ_ATTEMPTS)+1):
                            facility_results['passedattempt'+str(i)] = 0
                        
                        # get the quizzes for the course
                        quiz_acts = Activity.objects.filter(type=Activity.QUIZ,section__course=course).exclude(section__order=0).values_list('digest', flat=True)
                        trackers = Tracker.objects.filter(submitted_date__gte=start_date, submitted_date__lte=end_date,digest__in=quiz_acts, user__userprofile__location=facility)
                    
                        # get the total no people who passed/failed the quiz during this time
                        users_passed = []
                        users_failed = []
                        user_passed_attempts = {}
                        for i in range(1,int(settings.ISCHOOL_MAX_QUIZ_ATTEMPTS)+1):
                            user_passed_attempts['passedattempt'+str(i)] = []
                            
                        for counter, t in enumerate(trackers):
                            # check it's not more than the users 3rd attempt
                            no_previous_attempts = Tracker.objects.filter(submitted_date__lt=t.submitted_date,user=t.user,digest=t.digest).count()
                            if no_previous_attempts > (settings.ISCHOOL_MAX_QUIZ_ATTEMPTS-1):
                                continue
                            
                            if t.completed == True:
                                if t.user not in users_passed:
                                    users_passed.append(t.user)
                                    user_passed_attempts['passedattempt'+str(counter+1)].append(t.user)
                            else:
                                if t.user not in users_failed:
                                    users_failed.append(t.user)
            
                        users_failed = list(set(users_failed) - set(users_passed))
                                
                        facility_results['passed'] = users_passed
                        facility_results['failed'] = users_failed  
                        facility_results['total'] = len(users_failed) + len(users_passed)
                        
                        for i in range(1,int(settings.ISCHOOL_MAX_QUIZ_ATTEMPTS)+1):
                            facility_results['passedattempt'+str(i)] = set(user_passed_attempts['passedattempt'+str(i)])
                        
                 
                        district_results['passed'] += len(users_passed)
                        district_results['failed'] += len(users_failed)
                        district_results['total'] += len(users_failed) + len(users_passed)
                        
                        for i in range(1,int(settings.ISCHOOL_MAX_QUIZ_ATTEMPTS)+1):
                            district_results['passedattempt'+str(i)] += len(facility_results['passedattempt'+str(i)])
                        
                        district_results['facilities'].append(facility_results)
                        
                        
                    result['districts'].append(district_results)
                results.append(result)   
                
                # Create the totals for the course (all districts)
                course_summary = {}
                course_summary['passed'] = 0
                course_summary['failed'] = 0
                course_summary['total'] = 0
                
                for i in range(1,int(settings.ISCHOOL_MAX_QUIZ_ATTEMPTS)+1):
                    course_summary['passedattempt'+str(i)] = 0
                 
                for d in result['districts']:
                    course_summary['passed'] += d['passed']
                    course_summary['failed'] += d['failed']
                    course_summary['total'] += d['total']
                    for i in range(1,int(settings.ISCHOOL_MAX_QUIZ_ATTEMPTS)+1):
                           course_summary['passedattempt'+str(i)] += d['passedattempt'+str(i)]
                           
                result['course_summary'] = course_summary
                
            return render_to_response('oppia/reports/pass-rate-by-course.html',
                                  {'results': results,
                                   'form': form,
                                   'start_date': start_date,
                                   'end_date': end_date,
                                   'province': province,
                                   }, 
                                  context_instance=RequestContext(request))
        return render_to_response('oppia/reports/pass-rate-by-course.html',
                                  {'form': form,
                                   'start_date': start_date,
                                   'end_date': end_date,
                                   }, 
                                  context_instance=RequestContext(request))
    else:
        data = {}
        data['start_date'] = start_date
        data['end_date'] = end_date
        form = ProvinceDateDiffForm(initial=data)
        form.fields['provinces'].choices = [(p.id,p.name) for p in reporting_province_access(request.user)]
        
        dashboard_accessed.send(sender=None, request=request, data=None)
        
        return render_to_response('oppia/reports/pass-rate-by-course.html',
                                  {'form': form,
                                   'start_date': start_date,
                                   'end_date': end_date,
                                   }, 
                                  context_instance=RequestContext(request))