Example #1
0
    def post(self, request):  # lint-amnesty, pylint: disable=missing-function-docstring
        serializer = BulkEnrollmentSerializer(data=request.data)
        if serializer.is_valid():  # lint-amnesty, pylint: disable=too-many-nested-blocks
            # Setting the content type to be form data makes Django Rest Framework v3.6.3 treat all passed JSON data as
            # POST parameters. This is necessary because this request is forwarded on to the student_update_enrollment
            # view, which requires all of the parameters to be passed in via POST parameters.
            metadata = request._request.META  # pylint: disable=protected-access
            metadata['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'

            response_dict = {
                'auto_enroll': serializer.data.get('auto_enroll'),
                'email_students': serializer.data.get('email_students'),
                'action': serializer.data.get('action'),
                'courses': {}
            }
            for course_id, cohort_name in zip_longest(
                    serializer.data.get('courses'),
                    serializer.data.get('cohorts', [])):
                response = students_update_enrollment(self.request,
                                                      course_id=course_id)
                response_content = json.loads(response.content.decode('utf-8'))

                if cohort_name:
                    try:
                        course_key = CourseKey.from_string(course_id)
                        cohort = get_cohort_by_name(course_key=course_key,
                                                    name=cohort_name)
                    except (CourseUserGroup.DoesNotExist,
                            InvalidKeyError) as exc:
                        return Response(exc.message,
                                        status=status.HTTP_400_BAD_REQUEST)

                    for user_data in response_content['results']:
                        if "after" in user_data and (
                                user_data["after"].get("enrollment", False) is
                                True or user_data["after"].get(
                                    "allowed", False) is True):
                            user_id = user_data['identifier']
                            try:
                                _user_obj, previous_cohort, _pre_assigned = add_user_to_cohort(
                                    cohort, user_id)
                            except ValueError:
                                # User already present in cohort
                                previous_cohort = cohort_name

                            if previous_cohort:
                                user_data['before']['cohort'] = previous_cohort
                            else:
                                user_data['before']['cohort'] = None
                            user_data['after']['cohort'] = cohort_name

                response_dict['courses'][course_id] = response_content
            return Response(data=response_dict, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
Example #2
0
    def test_course_list_serializer(self):
        """
        Test that the course serializer will work when passed a string or list.

        Internally, DRF passes the data into the value conversion method as a list instead of
        a string, so StringListField needs to work with both.
        """
        for key in [self.course_key, [self.course_key]]:
            serializer = BulkEnrollmentSerializer(data={
                'identifiers': 'percivaloctavius',
                'action': 'enroll',
                'email_students': False,
                'courses': key,
            })
            assert serializer.is_valid()