learner_achievements.py 2.36 KB
Newer Older
1 2 3 4 5 6
"""
Views to render a learner's achievements.
"""

from django.template.loader import render_to_string
from lms.djangoapps.certificates import api as certificate_api
7
from openedx.core.djangoapps.certificates.api import certificates_viewable_for_course
8
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
from openedx.core.djangoapps.plugin_api.views import EdxFragmentView
from web_fragments.fragment import Fragment


class LearnerAchievementsFragmentView(EdxFragmentView):
    """
    A fragment to render a learner's achievements.
    """
    def render_to_fragment(self, request, username=None, own_profile=False, **kwargs):
        """
        Renders the current learner's achievements.
        """
        course_certificates = self._get_ordered_certificates_for_user(request, username)
        context = {
            'course_certificates': course_certificates,
            'own_profile': own_profile,
            'disable_courseware_js': True,
        }
        if course_certificates or own_profile:
            html = render_to_string('learner_profile/learner-achievements-fragment.html', context)
            return Fragment(html)
        else:
            return None

    def _get_ordered_certificates_for_user(self, request, username):
        """
        Returns a user's certificates sorted by course name.
        """
        course_certificates = certificate_api.get_certificates_for_user(username)
38
        passing_certificates = []
39
        for course_certificate in course_certificates:
40 41 42 43 44
            if course_certificate.get('is_passing', False):
                course_key = course_certificate['course_key']
                try:
                    course_overview = CourseOverview.get_from_id(course_key)
                    course_certificate['course'] = course_overview
45 46
                    if certificates_viewable_for_course(course_overview):
                        passing_certificates.append(course_certificate)
47 48 49 50 51 52 53
                except CourseOverview.DoesNotExist:
                    # This is unlikely to fail as the course should exist.
                    # Ideally the cert should have all the information that
                    # it needs. This might be solved by the Credentials API.
                    pass
        passing_certificates.sort(key=lambda certificate: certificate['course'].display_name_with_default)
        return passing_certificates