def handle(self, *args, **options):
        request_factory = RequestFactory()
        request = request_factory.get('/')
        request.user = User(email='*****@*****.**',
                            username='******',
                            password='******',
                            is_active=True)

        course_groups = api_models.CourseGroupRelationship.objects.all()
        for cg in course_groups:  # pylint: disable=C0103
            course_id = cg.course_id
            course_descriptor, course_key, course_content = get_course(
                request, request.user, course_id)  # pylint: disable=W0612
            cg.course_id = unicode(course_key)
            cg.save()

        course_content_groups = api_models.CourseContentGroupRelationship.objects.all(
        )
        for ccg in course_content_groups:
            course_id = ccg.course_id
            course_descriptor, course_key, course_content = get_course(
                request, request.user, course_id)
            ccg.course_id = unicode(course_key)
            try:
                ccg.content_id = course_key.make_usage_key_from_deprecated_string(
                    ccg.content_id)
            except InvalidKeyError:
                log.warning(
                    'Unable to convert content_id "{}"'.format(ccg.content_id),  # pylint: disable=W1202
                    exc_info=True)
                pass  # If the key conversion fails it was either a new-style key or junk data  # pylint: disable=W0107
            ccg.save()

        course_module_completions = CourseModuleCompletion.objects.all()
        for cmc in course_module_completions:
            course_id = cmc.course_id
            course_descriptor, course_key, course_content = get_course(
                request, request.user, course_id)
            cmc.course_id = unicode(course_key)
            try:
                cmc.content_id = course_key.make_usage_key_from_deprecated_string(
                    cmc.content_id)
            except InvalidKeyError:
                log.warning(
                    'Unable to convert content_id "{}"'.format(cmc.content_id),  # pylint: disable=W1202
                    exc_info=True)
                pass  # If the key conversion fails it was either a new-style key or junk data  # pylint: disable=W0107
            cmc.save()
Пример #2
0
    def post(self, request, group_id):
        """
        POST /api/groups/{group_id}/courses/
        """
        response_data = {}
        try:
            existing_group = Group.objects.get(id=group_id)
        except ObjectDoesNotExist:
            return Response({}, status.HTTP_404_NOT_FOUND)

        course_id = request.data.get('course_id', None)
        if not course_id:
            return Response({'message': _('course_id is missing')}, status=status.HTTP_400_BAD_REQUEST)

        base_uri = generate_base_uri(request)
        response_data['uri'] = '{}/{}'.format(base_uri, course_id)

        existing_course, course_key, course_content = get_course(request, request.user, course_id)  # pylint: disable=W0612,C0301
        if not existing_course:
            return Response({}, status.HTTP_404_NOT_FOUND)

        try:
            existing_relationship = CourseGroupRelationship.objects.get(course_id=course_id, group=existing_group)
        except ObjectDoesNotExist:
            existing_relationship = None

        if existing_relationship is None:
            new_relationship = CourseGroupRelationship.objects.create(course_id=course_id, group=existing_group)
            response_data['group_id'] = str(new_relationship.group_id)
            response_data['course_id'] = str(new_relationship.course_id)
            response_status = status.HTTP_201_CREATED
        else:
            response_data['message'] = "Relationship already exists."
            response_status = status.HTTP_409_CONFLICT
        return Response(response_data, status=response_status)
Пример #3
0
 def get(self, request, group_id):
     """
     GET /api/groups/{group_id}/courses/
     """
     response_data = {}
     try:
         existing_group = Group.objects.get(id=group_id)
     except ObjectDoesNotExist:
         return Response({}, status.HTTP_404_NOT_FOUND)
     members = CourseGroupRelationship.objects.filter(group=existing_group)
     response_data = []
     for member in members:
         course, course_key, course_content = get_course(request, request.user, member.course_id)  # pylint: disable=W0612,C0301
         course_data = {
             'course_id': member.course_id,
             'display_name': course.display_name
         }
         response_data.append(course_data)
     response_status = status.HTTP_200_OK
     return Response(response_data, status=response_status)
Пример #4
0
    def _validate_data(self, request, errors, new):
        """
        Validate imported data.
        :param new: if `True`, new user will be created and enrolled, otherwise existing user will be enrolled
        :returns `request.data` copy with added `course`, `course_key` and ('company` if `new` else `user_object`)
        """

        validated_data = request.data.copy()
        internal = validated_data.get('internal', False)
        statuses = validated_data.get('statuses', [])
        company_id = validated_data.get('company_id', '')
        course_id = validated_data.get('course_id', '')
        status = validated_data.get('status', '').lower()
        user = validated_data.get('user', {})
        username, email = user.get('username', ''), user.get('email', '')

        # Check for empty fields.
        for key, value in user.items():
            if not isinstance(value, bool) and value.strip() == '':
                if key != 'username':
                    self._add_error(errors,
                                    _("Empty field: {}").format(key),
                                    _("Processing Participant"), email)

        # Ensure valid status.
        if status not in statuses:
            self._add_error(errors,
                            _("Status '{}' doesn't exist").format(status),
                            _('Enrolling Participant in Course'), email)

        if new:
            # Ensure email/username integrity.
            if User.objects.filter(Q(email=email)
                                   | Q(username=username)).exists():
                self._add_error(
                    errors,
                    _('Email "{}" or username "{}" already exists').format(
                        email, username), _('Registering Participant'), email)

            # Check that the company exists.
            try:
                validated_data['company'] = Organization.objects.get(
                    id=company_id)
            except Organization.DoesNotExist:
                self._add_error(
                    errors,
                    _("Company {} doesn't exist").format(company_id),
                    _('Enrolling Participant in Company'), email)
        else:
            # Ensure user with provided email exists.
            try:
                validated_data['user_object'] = User.objects.get(email=email)
            except User.DoesNotExist:
                self._add_error(
                    errors,
                    _('User with email "{}" does not exist').format(email),
                    _('Retrieving existing Participant'), email)

            # Check if course is already enrolled.
            if validated_data.get('user_object',
                                  None) and CourseEnrollment.is_enrolled(
                                      validated_data.get('user_object'),
                                      CourseKey.from_string(course_id)):
                self._add_error(
                    errors,
                    _('User with email "{}" is already enrolled').format(
                        email), _("Enrolling Participant in Course"), email)

        # Check that the course exists.
        validated_data['course'], validated_data[
            'course_key'], __ = get_course(request, user, course_id)
        if not validated_data['course']:
            self._add_error(errors,
                            _("Course {} doesn't exist").format(course_id),
                            _('Enrolling Participant in Course'), email)

        # Check if course is internal (if required).
        if internal and not CourseGroupRelationship.objects.filter(
                course_id=course_id,
                group__groupprofile__group_type="tag:internal").exists():
            self._add_error(errors,
                            _("Course {} is not Internal").format(course_id),
                            _('Enrolling Participant in Course'), email)

        return validated_data