def handle(self, *args, **options):
        username = args[0]
        print username

        our_options = dict((k, v) for k, v in options.items()
                           if Command.is_valid_option(k) and v is not None)
        student = User.objects.get(username=username)
        try:
            testcenter_user = TestCenterUser.objects.get(user=student)
            needs_updating = testcenter_user.needs_update(our_options)
        except TestCenterUser.DoesNotExist:
            # do additional initialization here:
            testcenter_user = TestCenterUser.create(student)
            needs_updating = True

        if needs_updating:
            # the registration form normally populates the data dict with
            # all values from the testcenter_user.  But here we only want to
            # specify those values that change, so update the dict with existing
            # values.
            form_options = dict(our_options)
            for propname in TestCenterUser.user_provided_fields():
                if propname not in form_options:
                    form_options[
                        propname] = testcenter_user.__getattribute__(propname)
            form = TestCenterUserForm(
                instance=testcenter_user, data=form_options)
            if form.is_valid():
                form.update_and_save()
            else:
                errorlist = []
                if (len(form.errors) > 0):
                    errorlist.append("Field Form errors encountered:")
                    for fielderror in form.errors:
                        errorlist.append(
                            "Field Form Error:  {}".format(fielderror))
                if (len(form.non_field_errors()) > 0):
                    errorlist.append("Non-field Form errors encountered:")
                    for nonfielderror in form.non_field_errors:
                        errorlist.append(
                            "Non-field Form Error:  {}".format(nonfielderror))
                raise CommandError("\n".join(errorlist))
        else:
            print "No changes necessary to make to existing user's demographics."

        # override internal values:
        change_internal = False
        testcenter_user = TestCenterUser.objects.get(user=student)
        for internal_field in ['upload_error_message', 'upload_status', 'client_candidate_id']:
            if internal_field in our_options:
                testcenter_user.__setattr__(
                    internal_field, our_options[internal_field])
                change_internal = True

        if change_internal:
            testcenter_user.save()
            print "Updated  confirmation information in existing user's demographics."
        else:
            print "No changes necessary to make to confirmation information in existing user's demographics."
    def handle(self, *args, **options):
        username = args[0]
        print username

        our_options = dict((k, v) for k, v in options.items()
                           if Command.is_valid_option(k) and v is not None)
        student = User.objects.get(username=username)
        try:
            testcenter_user = TestCenterUser.objects.get(user=student)
            needs_updating = testcenter_user.needs_update(our_options)
        except TestCenterUser.DoesNotExist:
            # do additional initialization here:
            testcenter_user = TestCenterUser.create(student)
            needs_updating = True

        if needs_updating:
            # the registration form normally populates the data dict with
            # all values from the testcenter_user.  But here we only want to
            # specify those values that change, so update the dict with existing
            # values.
            form_options = dict(our_options)
            for propname in TestCenterUser.user_provided_fields():
                if propname not in form_options:
                    form_options[propname] = testcenter_user.__getattribute__(
                        propname)
            form = TestCenterUserForm(instance=testcenter_user,
                                      data=form_options)
            if form.is_valid():
                form.update_and_save()
            else:
                errorlist = []
                if (len(form.errors) > 0):
                    errorlist.append("Field Form errors encountered:")
                    for fielderror in form.errors:
                        errorlist.append(
                            "Field Form Error:  {}".format(fielderror))
                if (len(form.non_field_errors()) > 0):
                    errorlist.append("Non-field Form errors encountered:")
                    for nonfielderror in form.non_field_errors:
                        errorlist.append(
                            "Non-field Form Error:  {}".format(nonfielderror))
                raise CommandError("\n".join(errorlist))
        else:
            print "No changes necessary to make to existing user's demographics."

        # override internal values:
        change_internal = False
        testcenter_user = TestCenterUser.objects.get(user=student)
        for internal_field in [
                'upload_error_message', 'upload_status', 'client_candidate_id'
        ]:
            if internal_field in our_options:
                testcenter_user.__setattr__(internal_field,
                                            our_options[internal_field])
                change_internal = True

        if change_internal:
            testcenter_user.save()
            print "Updated  confirmation information in existing user's demographics."
        else:
            print "No changes necessary to make to confirmation information in existing user's demographics."
def create_exam_registration(request, post_override=None):
    '''
    JSON call to create a test center exam registration.
    Called by form in test_center_register.html
    '''
    post_vars = post_override if post_override else request.POST

    # first determine if we need to create a new TestCenterUser, or if we are making any update
    # to an existing TestCenterUser.
    username = post_vars['username']
    user = User.objects.get(username=username)
    course_id = post_vars['course_id']
    course = course_from_id(course_id)  # assume it will be found....

    # make sure that any demographic data values received from the page have been stripped.
    # Whitespace is not an acceptable response for any of these values
    demographic_data = {}
    for fieldname in TestCenterUser.user_provided_fields():
        if fieldname in post_vars:
            demographic_data[fieldname] = (post_vars[fieldname]).strip()
    try:
        testcenter_user = TestCenterUser.objects.get(user=user)
        needs_updating = testcenter_user.needs_update(demographic_data)
        log.info("User {0} enrolled in course {1} {2}updating demographic info for exam registration".format(user.username, course_id, "" if needs_updating else "not "))
    except TestCenterUser.DoesNotExist:
        # do additional initialization here:
        testcenter_user = TestCenterUser.create(user)
        needs_updating = True
        log.info("User {0} enrolled in course {1} creating demographic info for exam registration".format(user.username, course_id))

    # perform validation:
    if needs_updating:
        # first perform validation on the user information
        # using a Django Form.
        form = TestCenterUserForm(instance=testcenter_user, data=demographic_data)
        if form.is_valid():
            form.update_and_save()
        else:
            response_data = {'success': False}
            # return a list of errors...
            response_data['field_errors'] = form.errors
            response_data['non_field_errors'] = form.non_field_errors()
            return HttpResponse(json.dumps(response_data), mimetype="application/json")

    # create and save the registration:
    needs_saving = False
    exam = course.current_test_center_exam
    exam_code = exam.exam_series_code
    registrations = get_testcenter_registration(user, course_id, exam_code)
    if registrations:
        registration = registrations[0]
        # NOTE: we do not bother to check here to see if the registration has changed,
        # because at the moment there is no way for a user to change anything about their
        # registration.  They only provide an optional accommodation request once, and
        # cannot make changes to it thereafter.
        # It is possible that the exam_info content has been changed, such as the
        # scheduled exam dates, but those kinds of changes should not be handled through
        # this registration screen.

    else:
        accommodation_request = post_vars.get('accommodation_request', '')
        registration = TestCenterRegistration.create(testcenter_user, exam, accommodation_request)
        needs_saving = True
        log.info("User {0} enrolled in course {1} creating new exam registration".format(user.username, course_id))

    if needs_saving:
        # do validation of registration.  (Mainly whether an accommodation request is too long.)
        form = TestCenterRegistrationForm(instance=registration, data=post_vars)
        if form.is_valid():
            form.update_and_save()
        else:
            response_data = {'success': False}
            # return a list of errors...
            response_data['field_errors'] = form.errors
            response_data['non_field_errors'] = form.non_field_errors()
            return HttpResponse(json.dumps(response_data), mimetype="application/json")

    # only do the following if there is accommodation text to send,
    # and a destination to which to send it.
    # TODO: still need to create the accommodation email templates
#    if 'accommodation_request' in post_vars and 'TESTCENTER_ACCOMMODATION_REQUEST_EMAIL' in settings:
#        d = {'accommodation_request': post_vars['accommodation_request'] }
#
#        # composes accommodation email
#        subject = render_to_string('emails/accommodation_email_subject.txt', d)
#        # Email subject *must not* contain newlines
#        subject = ''.join(subject.splitlines())
#        message = render_to_string('emails/accommodation_email.txt', d)
#
#        try:
#            dest_addr = settings['TESTCENTER_ACCOMMODATION_REQUEST_EMAIL']
#            from_addr = user.email
#            send_mail(subject, message, from_addr, [dest_addr], fail_silently=False)
#        except:
#            log.exception(sys.exc_info())
#            response_data = {'success': False}
#            response_data['non_field_errors'] =  [ 'Could not send accommodation e-mail.', ]
#            return HttpResponse(json.dumps(response_data), mimetype="application/json")

    js = {'success': True}
    return HttpResponse(json.dumps(js), mimetype="application/json")
Exemple #4
0
def create_exam_registration(request, post_override=None):
    '''
    JSON call to create a test center exam registration.
    Called by form in test_center_register.html
    '''
    post_vars = post_override if post_override else request.POST

    # first determine if we need to create a new TestCenterUser, or if we are making any update
    # to an existing TestCenterUser.
    username = post_vars['username']
    user = User.objects.get(username=username)
    course_id = post_vars['course_id']
    course = course_from_id(course_id)  # assume it will be found....

    # make sure that any demographic data values received from the page have been stripped.
    # Whitespace is not an acceptable response for any of these values
    demographic_data = {}
    for fieldname in TestCenterUser.user_provided_fields():
        if fieldname in post_vars:
            demographic_data[fieldname] = (post_vars[fieldname]).strip()
    try:
        testcenter_user = TestCenterUser.objects.get(user=user)
        needs_updating = testcenter_user.needs_update(demographic_data)
        log.info(
            "User {0} enrolled in course {1} {2}updating demographic info for exam registration"
            .format(user.username, course_id,
                    "" if needs_updating else "not "))
    except TestCenterUser.DoesNotExist:
        # do additional initialization here:
        testcenter_user = TestCenterUser.create(user)
        needs_updating = True
        log.info(
            "User {0} enrolled in course {1} creating demographic info for exam registration"
            .format(user.username, course_id))

    # perform validation:
    if needs_updating:
        # first perform validation on the user information
        # using a Django Form.
        form = TestCenterUserForm(instance=testcenter_user,
                                  data=demographic_data)
        if form.is_valid():
            form.update_and_save()
        else:
            response_data = {'success': False}
            # return a list of errors...
            response_data['field_errors'] = form.errors
            response_data['non_field_errors'] = form.non_field_errors()
            return HttpResponse(json.dumps(response_data),
                                mimetype="application/json")

    # create and save the registration:
    needs_saving = False
    exam = course.current_test_center_exam
    exam_code = exam.exam_series_code
    registrations = get_testcenter_registration(user, course_id, exam_code)
    if registrations:
        registration = registrations[0]
        # NOTE: we do not bother to check here to see if the registration has changed,
        # because at the moment there is no way for a user to change anything about their
        # registration.  They only provide an optional accommodation request once, and
        # cannot make changes to it thereafter.
        # It is possible that the exam_info content has been changed, such as the
        # scheduled exam dates, but those kinds of changes should not be handled through
        # this registration screen.

    else:
        accommodation_request = post_vars.get('accommodation_request', '')
        registration = TestCenterRegistration.create(testcenter_user, exam,
                                                     accommodation_request)
        needs_saving = True
        log.info(
            "User {0} enrolled in course {1} creating new exam registration".
            format(user.username, course_id))

    if needs_saving:
        # do validation of registration.  (Mainly whether an accommodation request is too long.)
        form = TestCenterRegistrationForm(instance=registration,
                                          data=post_vars)
        if form.is_valid():
            form.update_and_save()
        else:
            response_data = {'success': False}
            # return a list of errors...
            response_data['field_errors'] = form.errors
            response_data['non_field_errors'] = form.non_field_errors()
            return HttpResponse(json.dumps(response_data),
                                mimetype="application/json")

    # only do the following if there is accommodation text to send,
    # and a destination to which to send it.
    # TODO: still need to create the accommodation email templates


#    if 'accommodation_request' in post_vars and 'TESTCENTER_ACCOMMODATION_REQUEST_EMAIL' in settings:
#        d = {'accommodation_request': post_vars['accommodation_request'] }
#
#        # composes accommodation email
#        subject = render_to_string('emails/accommodation_email_subject.txt', d)
#        # Email subject *must not* contain newlines
#        subject = ''.join(subject.splitlines())
#        message = render_to_string('emails/accommodation_email.txt', d)
#
#        try:
#            dest_addr = settings['TESTCENTER_ACCOMMODATION_REQUEST_EMAIL']
#            from_addr = user.email
#            send_mail(subject, message, from_addr, [dest_addr], fail_silently=False)
#        except:
#            log.exception(sys.exc_info())
#            response_data = {'success': False}
#            response_data['non_field_errors'] =  [ 'Could not send accommodation e-mail.', ]
#            return HttpResponse(json.dumps(response_data), mimetype="application/json")

    js = {'success': True}
    return HttpResponse(json.dumps(js), mimetype="application/json")