def handle(self, *args, **options): username = args[0] course_id = args[1] print username, course_id our_options = dict((k, v) for k, v in options.items() if Command.is_valid_option(k) and v is not None) try: student = User.objects.get(username=username) except User.DoesNotExist: raise CommandError("User \"{}\" does not exist".format(username)) try: testcenter_user = TestCenterUser.objects.get(user=student) except TestCenterUser.DoesNotExist: raise CommandError("User \"{}\" does not have an existing demographics record".format(username)) # get an "exam" object. Check to see if a course_id was specified, and use information from that: exam = None create_dummy_exam = 'create_dummy_exam' in our_options and our_options['create_dummy_exam'] if not create_dummy_exam: try: course = course_from_id(course_id) if 'ignore_registration_dates' in our_options: examlist = [exam for exam in course.test_center_exams if exam.exam_series_code == our_options.get('exam_series_code')] exam = examlist[0] if len(examlist) > 0 else None else: exam = course.current_test_center_exam except ItemNotFoundError: pass else: # otherwise use explicit values (so we don't have to define a course): exam_name = "Dummy Placeholder Name" exam_info = {'Exam_Series_Code': our_options['exam_series_code'], 'First_Eligible_Appointment_Date': our_options['eligibility_appointment_date_first'], 'Last_Eligible_Appointment_Date': our_options['eligibility_appointment_date_last'], } exam = CourseDescriptor.TestCenterExam(course_id, exam_name, exam_info) # update option values for date_first and date_last to use YYYY-MM-DD format # instead of YYYY-MM-DDTHH:MM our_options['eligibility_appointment_date_first'] = strftime("%Y-%m-%d", exam.first_eligible_appointment_date) our_options['eligibility_appointment_date_last'] = strftime("%Y-%m-%d", exam.last_eligible_appointment_date) if exam is None: raise CommandError("Exam for course_id {} does not exist".format(course_id)) exam_code = exam.exam_series_code UPDATE_FIELDS = ('accommodation_request', 'accommodation_code', 'client_authorization_id', 'exam_series_code', 'eligibility_appointment_date_first', 'eligibility_appointment_date_last', ) # create and save the registration: needs_updating = False registrations = get_testcenter_registration(student, course_id, exam_code) if len(registrations) > 0: registration = registrations[0] for fieldname in UPDATE_FIELDS: if fieldname in our_options and registration.__getattribute__(fieldname) != our_options[fieldname]: needs_updating = True; else: accommodation_request = our_options.get('accommodation_request', '') registration = TestCenterRegistration.create(testcenter_user, exam, accommodation_request) needs_updating = True if needs_updating: # first update the record with the new values, if any: for fieldname in UPDATE_FIELDS: if fieldname in our_options and fieldname not in TestCenterRegistrationForm.Meta.fields: registration.__setattr__(fieldname, our_options[fieldname]) # the registration form normally populates the data dict with # the accommodation request (if any). But here we want to # specify only those values that might change, so update the dict with existing # values. form_options = dict(our_options) for propname in TestCenterRegistrationForm.Meta.fields: if propname not in form_options: form_options[propname] = registration.__getattribute__(propname) form = TestCenterRegistrationForm(instance=registration, data=form_options) if form.is_valid(): form.update_and_save() print "Updated registration information for user's registration: username \"{}\" course \"{}\", examcode \"{}\"".format(student.username, course_id, exam_code) else: if (len(form.errors) > 0): print "Field Form errors encountered:" for fielderror in form.errors: for msg in form.errors[fielderror]: print "Field Form Error: {} -- {}".format(fielderror, msg) if (len(form.non_field_errors()) > 0): print "Non-field Form errors encountered:" for nonfielderror in form.non_field_errors: print "Non-field Form Error: %s" % nonfielderror else: print "No changes necessary to make to existing user's registration." # override internal values: change_internal = False if 'exam_series_code' in our_options: exam_code = our_options['exam_series_code'] registration = get_testcenter_registration(student, course_id, exam_code)[0] for internal_field in ['upload_error_message', 'upload_status', 'authorization_id']: if internal_field in our_options: registration.__setattr__(internal_field, our_options[internal_field]) change_internal = True if change_internal: print "Updated confirmation information in existing user's registration." registration.save() else: print "No changes necessary to make to confirmation information in existing user's registration."
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")
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")