def test_registered_for_course(self): self.assertFalse(views.registered_for_course('Basketweaving', None)) mock_user = MagicMock() mock_user.is_authenticated.return_value = False self.assertFalse(views.registered_for_course('dummy', mock_user)) mock_course = MagicMock() mock_course.id = self.course_key self.assertTrue(views.registered_for_course(mock_course, self.user))
def register_code_redemption(request, registration_code): """ This view allows the student to redeem the registration code and enroll in the course. """ # Add some rate limiting here by re-using the RateLimitMixin as a helper class site_name = microsite.get_value('SITE_NAME', settings.SITE_NAME) limiter = BadRequestRateLimiter() if limiter.is_rate_limit_exceeded(request): AUDIT_LOG.warning( "Rate limit exceeded in registration code redemption.") return HttpResponseForbidden() template_to_render = 'shoppingcart/registration_code_receipt.html' if request.method == "GET": reg_code_is_valid, reg_code_already_redeemed, course_registration = get_reg_code_validity( registration_code, request, limiter) course = get_course_by_id(getattr(course_registration, 'course_id'), depth=0) context = { 'reg_code_already_redeemed': reg_code_already_redeemed, 'reg_code_is_valid': reg_code_is_valid, 'reg_code': registration_code, 'site_name': site_name, 'course': course, 'registered_for_course': registered_for_course(course, request.user) } return render_to_response(template_to_render, context) elif request.method == "POST": reg_code_is_valid, reg_code_already_redeemed, course_registration = get_reg_code_validity( registration_code, request, limiter) course = get_course_by_id(getattr(course_registration, 'course_id'), depth=0) if reg_code_is_valid and not reg_code_already_redeemed: #now redeem the reg code. RegistrationCodeRedemption.create_invoice_generated_registration_redemption( course_registration, request.user) CourseEnrollment.enroll(request.user, course.id) context = { 'redemption_success': True, 'reg_code': registration_code, 'site_name': site_name, 'course': course, } else: context = { 'reg_code_is_valid': reg_code_is_valid, 'reg_code_already_redeemed': reg_code_already_redeemed, 'redemption_success': False, 'reg_code': registration_code, 'site_name': site_name, 'course': course, } return render_to_response(template_to_render, context)
def register_code_redemption(request, registration_code): """ This view allows the student to redeem the registration code and enroll in the course. """ # Add some rate limiting here by re-using the RateLimitMixin as a helper class site_name = microsite.get_value('SITE_NAME', settings.SITE_NAME) limiter = BadRequestRateLimiter() if limiter.is_rate_limit_exceeded(request): AUDIT_LOG.warning("Rate limit exceeded in registration code redemption.") return HttpResponseForbidden() template_to_render = 'shoppingcart/registration_code_receipt.html' if request.method == "GET": reg_code_is_valid, reg_code_already_redeemed, course_registration = get_reg_code_validity(registration_code, request, limiter) course = get_course_by_id(getattr(course_registration, 'course_id'), depth=0) context = { 'reg_code_already_redeemed': reg_code_already_redeemed, 'reg_code_is_valid': reg_code_is_valid, 'reg_code': registration_code, 'site_name': site_name, 'course': course, 'registered_for_course': registered_for_course(course, request.user) } return render_to_response(template_to_render, context) elif request.method == "POST": reg_code_is_valid, reg_code_already_redeemed, course_registration = get_reg_code_validity(registration_code, request, limiter) course = get_course_by_id(getattr(course_registration, 'course_id'), depth=0) if reg_code_is_valid and not reg_code_already_redeemed: #now redeem the reg code. RegistrationCodeRedemption.create_invoice_generated_registration_redemption(course_registration, request.user) CourseEnrollment.enroll(request.user, course.id) context = { 'redemption_success': True, 'reg_code': registration_code, 'site_name': site_name, 'course': course, } else: context = { 'reg_code_is_valid': reg_code_is_valid, 'reg_code_already_redeemed': reg_code_already_redeemed, 'redemption_success': False, 'reg_code': registration_code, 'site_name': site_name, 'course': course, } return render_to_response(template_to_render, context)
def register_code_redemption(request, registration_code): """ This view allows the student to redeem the registration code and enroll in the course. """ # Add some rate limiting here by re-using the RateLimitMixin as a helper class site_name = microsite.get_value('SITE_NAME', settings.SITE_NAME) limiter = BadRequestRateLimiter() if limiter.is_rate_limit_exceeded(request): AUDIT_LOG.warning("Rate limit exceeded in registration code redemption.") return HttpResponseForbidden() template_to_render = 'shoppingcart/registration_code_redemption.html' if request.method == "GET": reg_code_is_valid, reg_code_already_redeemed, course_registration = get_reg_code_validity(registration_code, request, limiter) course = get_course_by_id(getattr(course_registration, 'course_id'), depth=0) context = { 'reg_code_already_redeemed': reg_code_already_redeemed, 'reg_code_is_valid': reg_code_is_valid, 'reg_code': registration_code, 'site_name': site_name, 'course': course, 'registered_for_course': registered_for_course(course, request.user) } return render_to_response(template_to_render, context) elif request.method == "POST": reg_code_is_valid, reg_code_already_redeemed, course_registration = get_reg_code_validity(registration_code, request, limiter) course = get_course_by_id(getattr(course_registration, 'course_id'), depth=0) if reg_code_is_valid and not reg_code_already_redeemed: # remove the course from the cart if it was added there. cart = Order.get_cart_for_user(request.user) try: cart_items = cart.find_item_by_course_id(course_registration.course_id) except ItemNotFoundInCartException: pass else: for cart_item in cart_items: if isinstance(cart_item, PaidCourseRegistration) or isinstance(cart_item, CourseRegCodeItem): cart_item.delete() #now redeem the reg code. redemption = RegistrationCodeRedemption.create_invoice_generated_registration_redemption(course_registration, request.user) redemption.course_enrollment = CourseEnrollment.enroll(request.user, course.id) redemption.save() context = { 'redemption_success': True, 'reg_code': registration_code, 'site_name': site_name, 'course': course, } else: context = { 'reg_code_is_valid': reg_code_is_valid, 'reg_code_already_redeemed': reg_code_already_redeemed, 'redemption_success': False, 'reg_code': registration_code, 'site_name': site_name, 'course': course, } return render_to_response(template_to_render, context)
def dashboard(request): user = request.user enrollments = CourseEnrollment.objects.filter(user=user) # Build our courses list for the user, but ignore any courses that no longer # exist (because the course IDs have changed). Still, we don't delete those # enrollments, because it could have been a data push snafu. courses = [] for enrollment in enrollments: try: courses.append(course_from_id(enrollment.course_id)) except ItemNotFoundError: log.error("User {0} enrolled in non-existent course {1}" .format(user.username, enrollment.course_id)) message = "" if not user.is_active: message = render_to_string('registration/activate_account_notice.html', {'email': user.email}) # Global staff can see what courses errored on their dashboard staff_access = False errored_courses = {} if has_access(user, 'global', 'staff'): # Show any courses that errored on load staff_access = True errored_courses = modulestore().get_errored_courses() show_courseware_links_for = frozenset(course.id for course in courses if has_access(request.user, course, 'load')) cert_statuses = {course.id: cert_info(request.user, course) for course in courses} exam_registrations = {course.id: exam_registration_info(request.user, course) for course in courses} # Get the 3 most recent news top_news = _get_news(top=3) if not settings.MITX_FEATURES.get('ENABLE_MKTG_SITE', False) else None username = str(request.user) #Recommended courses for the user cursor = connection.cursor() query_getuserid = "select id,username from auth_user where username='******'" user_id = -1; cursor.execute(query_getuserid) row = cursor.fetchall() for a in row: user_id = a[0] query = "select user_id,area_of_interest from auth_userprofile where user_id='"+str(user_id)+"'" cursor.execute(query) area_interest = "" row = cursor.fetchall() for a in row: area_interest = a[1] interested_category="" for code,categ in UserProfile.COURSE_CATEGORIES: if code == str(area_interest): interested_category = categ break query_course_category = "select courseName,courseCategory from course_categories where courseCategory='"+area_interest+"'" cursor.execute(query_course_category) row = cursor.fetchall() similar_category_courses = [] for a in row: similar_category_courses.append(a[0]) recommended_courses = get_courses(request.user, request.META.get('HTTP_HOST')) recommend_courses = [] for check_course in recommended_courses: registered = registered_for_course(check_course,request.user) loc = check_course.location reverse_loc = loc[::-1] for simCourse in similar_category_courses: if simCourse == str(reverse_loc[1]): if not registered: recommend_courses.append(check_course) recommended_courses = sort_by_announcement(recommended_courses) context = {'courses': courses, 'recommended_courses': recommend_courses, 'message': message, 'staff_access': staff_access, 'errored_courses': errored_courses, 'show_courseware_links_for': show_courseware_links_for, 'cert_statuses': cert_statuses, 'news': top_news, 'exam_registrations': exam_registrations, 'categ':interested_category, } return render_to_response('dashboard.html', context)
def course_courseware(request, course_id, chapter = None, section = None, position = None): if not request.user.is_authenticated(): return JsonResponse({ "status": False }) course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id) user = User.objects.prefetch_related("groups").get(id = request.user.id) request.user = user # keep just one instance of User course = get_course_with_access(user, 'load', course_key, depth = 2) if not registered_for_course(course, user): # TODO (vshnayder): do course instructors need to be registered to see # course? return JsonResponse({ 'status': False }) try: field_data_cache = FieldDataCache.cache_for_descriptor_descendents(course_key, user, course, depth = 2) course_module = get_module_for_descriptor(user, request, course, field_data_cache, course_key) has_content = course.has_children_at_depth(2) if not has_content: # Show empty courseware for a course with no units return JsonResponse({ 'status': False }) if position is not None: try: int(position) except ValueError: return JsonResponse({ 'status': False }) def get_units(chapter, section, position = None): chapter_descriptor = course.get_child_by(lambda m: m.location.name == chapter) section_descriptor = chapter_descriptor.get_child_by(lambda m: m.location.name == section) # cdodge: this looks silly, but let's refetch the section_descriptor with depth=None # which will prefetch the children more efficiently than doing a recursive load section_descriptor = modulestore().get_item(section_descriptor.location, depth = None) section_field_data_cache = FieldDataCache.cache_for_descriptor_descendents(course_key, user, section_descriptor, depth = None) section_module = get_module_for_descriptor(request.user, request, section_descriptor, section_field_data_cache, course_key, position) if section_module is not None: units = [] for unit in section_module.get_display_items(): verticals = [] for vertical in unit.get_display_items(): if isinstance(vertical, VideoDescriptor): subtitles = vertical.transcripts.copy() if vertical.sub != "": subtitles.update({ 'en': sub }) verticals.append({ 'name': vertical.display_name, 'video_sources': vertical.html5_sources, 'subtitles': subtitles, 'type': 'video' }) else: verticals.append({ 'name': vertical.display_name, 'type': 'other' }) units.append({ 'name': unit.display_name, 'verticals': verticals }) return units else: return None if chapter is None or section is None: context = { 'course_id': course.id.to_deprecated_string(), 'sections': toc_for_course(user, request, course, chapter, section, field_data_cache), 'course_title': course.display_name_with_default, 'status': True } for chapter in context.get('sections', []): for section in chapter.get('sections', []): section.update({ 'units': get_units(chapter['url_name'], section['url_name'])}) else: units = get_units(chapter, section, position) context = { 'units': units, 'status': True if units is not None else False } except Exception as e: # In production, don't want to let a 500 out for any reason if settings.DEBUG: raise else: log.exception(u"Error in index view: user={user}, course={course}, chapter={chapter}" u" section={section} position={position}".format(user=user, course=course, chapter=chapter, section=section, position=position)) context = { 'status': False } return JsonResponse(context)
def register_code_redemption(request, registration_code): """ This view allows the student to redeem the registration code and enroll in the course. """ # Add some rate limiting here by re-using the RateLimitMixin as a helper class site_name = microsite.get_value('SITE_NAME', settings.SITE_NAME) limiter = BadRequestRateLimiter() if limiter.is_rate_limit_exceeded(request): AUDIT_LOG.warning("Rate limit exceeded in registration code redemption.") return HttpResponseForbidden() template_to_render = 'shoppingcart/registration_code_redemption.html' if request.method == "GET": reg_code_is_valid, reg_code_already_redeemed, course_registration = get_reg_code_validity(registration_code, request, limiter) course = get_course_by_id(getattr(course_registration, 'course_id'), depth=0) context = { 'reg_code_already_redeemed': reg_code_already_redeemed, 'reg_code_is_valid': reg_code_is_valid, 'reg_code': registration_code, 'site_name': site_name, 'course': course, 'registered_for_course': registered_for_course(course, request.user) } return render_to_response(template_to_render, context) elif request.method == "POST": reg_code_is_valid, reg_code_already_redeemed, course_registration = get_reg_code_validity(registration_code, request, limiter) course = get_course_by_id(getattr(course_registration, 'course_id'), depth=0) context = { 'reg_code': registration_code, 'site_name': site_name, 'course': course, 'reg_code_is_valid': reg_code_is_valid, 'reg_code_already_redeemed': reg_code_already_redeemed, } if reg_code_is_valid and not reg_code_already_redeemed: # remove the course from the cart if it was added there. cart = Order.get_cart_for_user(request.user) try: cart_items = cart.find_item_by_course_id(course_registration.course_id) except ItemNotFoundInCartException: pass else: for cart_item in cart_items: if isinstance(cart_item, PaidCourseRegistration) or isinstance(cart_item, CourseRegCodeItem): cart_item.delete() #now redeem the reg code. redemption = RegistrationCodeRedemption.create_invoice_generated_registration_redemption(course_registration, request.user) try: kwargs = {} if course_registration.mode_slug is not None: if CourseMode.mode_for_course(course.id, course_registration.mode_slug): kwargs['mode'] = course_registration.mode_slug else: raise RedemptionCodeError() redemption.course_enrollment = CourseEnrollment.enroll(request.user, course.id, **kwargs) redemption.save() context['redemption_success'] = True except RedemptionCodeError: context['redeem_code_error'] = True context['redemption_success'] = False except EnrollmentClosedError: context['enrollment_closed'] = True context['redemption_success'] = False except CourseFullError: context['course_full'] = True context['redemption_success'] = False except AlreadyEnrolledError: context['registered_for_course'] = True context['redemption_success'] = False else: context['redemption_success'] = False return render_to_response(template_to_render, context)