• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python views.course_from_id函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中student.views.course_from_id函数的典型用法代码示例。如果您正苦于以下问题:Python course_from_id函数的具体用法?Python course_from_id怎么用?Python course_from_id使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了course_from_id函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: load_single_user_time

def load_single_user_time(request):
    user = User.objects.get(id=request.POST.get('user_id'))
    row = {}
    rts = record_time_store()
    external_time = 0
    all_external_time = 0
    user_id = str(user.id)
    course_id = str(request.POST.get('course_id', None))
    if course_id:
        for enrollment in CourseEnrollment.enrollments_for_user(user):
            try:
                course = course_from_id(enrollment.course_id)
                all_external_time += rts.get_external_time(user_id, course.id)
            except ItemNotFoundError:
                #log.error("User {0} enrolled in non-existent course {1}".format(p.user.username, enrollment.course_id))
                pass
        all_course_time, all_discussion_time, portfolio_time = rts.get_stats_time(user_id)
        adjustment_time_totle = rts.get_adjustment_time(user_id, 'total', None)
        external_time = rts.get_external_time(user_id, course_id)
        course_time = rts.get_course_time(user_id, course_id, 'courseware')
        discussion_time = rts.get_course_time(user_id, course_id, 'discussion')
        collaboration_time = all_discussion_time + portfolio_time
        all_course_time = all_course_time + all_external_time
        total_time = all_course_time + collaboration_time + adjustment_time_totle
    else:
        for enrollment in CourseEnrollment.enrollments_for_user(user):
            try:
                course = course_from_id(enrollment.course_id)
                external_time += rts.get_external_time(user_id, course.id)
            except ItemNotFoundError:
                #log.error("User {0} enrolled in non-existent course {1}".format(p.user.username, enrollment.course_id))
                pass
        adjustment_time_totle = rts.get_adjustment_time(user_id, 'total', None)
        course_time, discussion_time, portfolio_time = rts.get_stats_time(user_id)
        all_course_time = course_time + external_time
        collaboration_time = discussion_time + portfolio_time
        total_time = all_course_time + collaboration_time + adjustment_time_totle

    row = {"id": user_id,
           "total_time": study_time_format(total_time, True),
           "collaboration_time": study_time_format(collaboration_time, True),
           "discussion_time": study_time_format(discussion_time, True),
           "portfolio_time": study_time_format(portfolio_time, True),
           "external_time": study_time_format(external_time, True),
           "course_time": study_time_format(course_time, True)
           }

    return HttpResponse(json.dumps({'row': row}), content_type="application/json")
开发者ID:EduPepperPDTesting,项目名称:pepper2013-testing,代码行数:48,代码来源:time_report.py


示例2: get

    def get(self, request, course_id):
        """
        Handle the case where we have a get request
        """
        upgrade = request.GET.get('upgrade', False)
        if CourseEnrollment.enrollment_mode_for_user(request.user, course_id) == 'verified':
            return redirect(reverse('dashboard'))
        verify_mode = CourseMode.mode_for_course(course_id, "verified")
        if course_id in request.session.get("donation_for_course", {}):
            chosen_price = request.session["donation_for_course"][course_id]
        else:
            chosen_price = verify_mode.min_price.format("{:g}")

        course = course_from_id(course_id)
        context = {
            "course_id": course_id,
            "course_name": course.display_name_with_default,
            "course_org": course.display_org_with_default,
            "course_num": course.display_number_with_default,
            "purchase_endpoint": get_purchase_endpoint(),
            "currency": verify_mode.currency.upper(),
            "chosen_price": chosen_price,
            "upgrade": upgrade,
        }
        return render_to_response('verify_student/verified.html', context)
开发者ID:DazzaGreenwood,项目名称:edx-platform,代码行数:25,代码来源:views.py


示例3: validate_adjustment_time

def validate_adjustment_time(rts, user_id, type, adjustment_time, course_id):
    type_time = 0
    external_time = 0
    adjustment_time = int(adjustment_time)
    if adjustment_time < 0:
        if type == 'total':
            user = User.objects.get(id=user_id)
            for enrollment in CourseEnrollment.enrollments_for_user(user):
                try:
                    course = course_from_id(enrollment.course_id)
                    external_time += rts.get_external_time(user_id, course.id)
                except ItemNotFoundError:
                    log.error("User {0} enrolled in non-existent course {1}".format(user.username, enrollment.course_id))

            course_time, discussion_time, portfolio_time = rts.get_stats_time(user_id)
            adjustment_time_totle = rts.get_adjustment_time(user_id, 'total', None)
            type_time = course_time + discussion_time + portfolio_time + external_time + adjustment_time_totle
        else:
            if type == 'external':
                type_time = rts.get_external_time(user_id, course_id)
            else:
                type_time = rts.get_course_time(user_id, course_id, type)
        if type_time + adjustment_time < 0:
            return False
    return True
开发者ID:EduPepperPDTesting,项目名称:pepper2013-testing,代码行数:25,代码来源:time_report.py


示例4: get

    def get(self, request, course_id, error=None):
        """ Displays the course mode choice page """
        if CourseEnrollment.enrollment_mode_for_user(request.user, course_id) == 'verified':
            return redirect(reverse('dashboard'))
        modes = CourseMode.modes_for_course_dict(course_id)

        donation_for_course = request.session.get("donation_for_course", {})
        chosen_price = donation_for_course.get(course_id, None)

        course = course_from_id(course_id)
        context = {
            "course_id": course_id,
            "modes": modes,
            "course_name": course.display_name_with_default,
            "course_org": course.display_org_with_default,
            "course_num": course.display_number_with_default,
            "chosen_price": chosen_price,
            "error": error,
        }
        if "verified" in modes:
            context["suggested_prices"] = modes["verified"].suggested_prices.split(",")
            context["currency"] = modes["verified"].currency.upper()
            context["min_price"] = modes["verified"].min_price

        return render_to_response("course_modes/choose.html", context)
开发者ID:Cabris,项目名称:edx-platform,代码行数:25,代码来源:views.py


示例5: midcourse_reverify_dash

def midcourse_reverify_dash(request):
    """
    Shows the "course reverification dashboard", which displays the reverification status (must reverify,
    pending, approved, failed, etc) of all courses in which a student has a verified enrollment.
    """
    user = request.user
    course_enrollment_pairs = []
    for enrollment in CourseEnrollment.enrollments_for_user(user):
        try:
            course_enrollment_pairs.append((course_from_id(enrollment.course_id), enrollment))
        except ItemNotFoundError:
            log.error("User {0} enrolled in non-existent course {1}"
                      .format(user.username, enrollment.course_id))

    statuses = ["approved", "pending", "must_reverify", "denied"]

    reverifications = reverification_info(course_enrollment_pairs, user, statuses)

    context = {
        "user_full_name": user.profile.name,
        'reverifications': reverifications,
        'referer': request.META.get('HTTP_REFERER'),
        'billing_email': settings.PAYMENT_SUPPORT_EMAIL,
    }
    return render_to_response("verify_student/midcourse_reverify_dash.html", context)
开发者ID:DazzaGreenwood,项目名称:edx-platform,代码行数:25,代码来源:views.py


示例6: get

    def get(self, request, course_id, error=None):
        """ Displays the course mode choice page """

        enrollment_mode = CourseEnrollment.enrollment_mode_for_user(request.user, course_id)
        upgrade = request.GET.get('upgrade', False)

        # verified users do not need to register or upgrade
        if enrollment_mode == 'verified':
            return redirect(reverse('dashboard'))

        # registered users who are not trying to upgrade do not need to re-register
        if enrollment_mode is not None and upgrade is False:
            return redirect(reverse('dashboard'))

        modes = CourseMode.modes_for_course_dict(course_id)
        donation_for_course = request.session.get("donation_for_course", {})
        chosen_price = donation_for_course.get(course_id, None)

        course = course_from_id(course_id)
        context = {
            "course_id": course_id,
            "modes": modes,
            "course_name": course.display_name_with_default,
            "course_org": course.display_org_with_default,
            "course_num": course.display_number_with_default,
            "chosen_price": chosen_price,
            "error": error,
            "upgrade": upgrade,
        }
        if "verified" in modes:
            context["suggested_prices"] = [decimal.Decimal(x) for x in modes["verified"].suggested_prices.split(",")]
            context["currency"] = modes["verified"].currency.upper()
            context["min_price"] = modes["verified"].min_price

        return render_to_response("course_modes/choose.html", context)
开发者ID:DavidGrahamFL,项目名称:edx-platform,代码行数:35,代码来源:views.py


示例7: get

    def get(self, request, course_id):
        """
        Handle the case where we have a get request
        """
        upgrade = request.GET.get('upgrade', False)
        course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id)
        if CourseEnrollment.enrollment_mode_for_user(request.user, course_id) == 'verified':
            return redirect(reverse('dashboard'))
        verify_mode = CourseMode.mode_for_course(course_id, "verified")

        if verify_mode is None:
            return redirect(reverse('dashboard'))

        chosen_price = request.session.get(
            "donation_for_course",
            {}
        ).get(
            course_id.to_deprecated_string(),
            verify_mode.min_price
        )

        course = course_from_id(course_id)
        context = {
            "course_id": course_id.to_deprecated_string(),
            "course_modes_choose_url": reverse('course_modes_choose', kwargs={'course_id': course_id.to_deprecated_string()}),
            "course_name": course.display_name_with_default,
            "course_org": course.display_org_with_default,
            "course_num": course.display_number_with_default,
            "purchase_endpoint": get_purchase_endpoint(),
            "currency": verify_mode.currency.upper(),
            "chosen_price": chosen_price,
            "create_order_url": reverse("verify_student_create_order"),
            "upgrade": upgrade,
        }
        return render_to_response('verify_student/verified.html', context)
开发者ID:PaoloC68,项目名称:edx-platform,代码行数:35,代码来源:views.py


示例8: drop_courses

def drop_courses(request):
    r = list()
    courses = get_courses(None)
    for course in courses:
        course = course_from_id(course.id)
        r.append({"id": course.id, "name": str(course.display_coursenumber) + ' ' + course.display_name})
    r.sort(key=lambda x: x['name'], reverse=False)
    return HttpResponse(json.dumps(r), content_type="application/json")
开发者ID:EduPepperPDTesting,项目名称:pepper2013-testing,代码行数:8,代码来源:time_report.py


示例9: add_to_order

    def add_to_order(cls, order, course_id, mode_slug=CourseMode.DEFAULT_MODE_SLUG, cost=None, currency=None):
        """
        A standardized way to create these objects, with sensible defaults filled in.
        Will update the cost if called on an order that already carries the course.

        Returns the order item
        """
        # First a bunch of sanity checks
        try:
            course = course_from_id(course_id)  # actually fetch the course to make sure it exists, use this to
                                                # throw errors if it doesn't
        except ItemNotFoundError:
            log.error("User {} tried to add non-existent course {} to cart id {}"
                      .format(order.user.email, course_id, order.id))
            raise CourseDoesNotExistException

        if cls.contained_in_order(order, course_id):
            log.warning("User {} tried to add PaidCourseRegistration for course {}, already in cart id {}"
                        .format(order.user.email, course_id, order.id))
            raise ItemAlreadyInCartException

        if CourseEnrollment.is_enrolled(user=order.user, course_id=course_id):
            log.warning("User {} trying to add course {} to cart id {}, already registered"
                        .format(order.user.email, course_id, order.id))
            raise AlreadyEnrolledInCourseException

        ### Validations done, now proceed
        ### handle default arguments for mode_slug, cost, currency
        ## Se corrigio la llamada a CourseMode, para que lea la forma
        ## de pago que esta ligada a este curso
        course_list = CourseMode.modes_for_course(course_id)
        course_mode = course_list and course_list[0] or []
        if not course_mode:
            # user could have specified a mode that's not set, in that case return the DEFAULT_MODE
            course_mode = CourseMode.DEFAULT_MODE
        if not cost:
            cost = course_mode.min_price
        if not currency:
            currency = course_mode.currency

        super(PaidCourseRegistration, cls).add_to_order(order, course_id, cost, currency=currency)

        item, created = cls.objects.get_or_create(order=order, user=order.user, course_id=course_id)
        item.status = order.status
        item.mode = course_mode.slug
        item.qty = 1
        item.unit_cost = cost
        item.line_desc = _(u'Registration for Course: {course_name}').format(
            course_name=course.display_name_with_default)
        item.currency = currency
        order.currency = currency
        item.report_comments = item.csv_report_comments
        order.save()
        item.save()
        log.info("User {} added course registration {} to cart: order {}"
                 .format(order.user.email, course_id, order.id))
        return item
开发者ID:name1984,项目名称:edx-platform,代码行数:57,代码来源:models.py


示例10: single_item_receipt_context

 def single_item_receipt_context(self):
     course = course_from_id(self.course_id)
     return {
         "course_id" : self.course_id,
         "course_name": course.display_name_with_default,
         "course_org": course.display_org_with_default,
         "course_num": course.display_number_with_default,
         "course_start_date_text": course.start_date_text,
         "course_has_started": course.start > datetime.today().replace(tzinfo=pytz.utc),
     }
开发者ID:felipemontoya,项目名称:edx-platform,代码行数:10,代码来源:models.py


示例11: post

    def post(self, request, course_id):
        """ Takes the form submission from the page and parses it """
        user = request.user

        # This is a bit redundant with logic in student.views.change_enrollement,
        # but I don't really have the time to refactor it more nicely and test.
        course = course_from_id(course_id)
        if not has_access(user, course, 'enroll'):
            error_msg = _("Enrollment is closed")
            return self.get(request, course_id, error=error_msg)

        upgrade = request.GET.get('upgrade', False)

        requested_mode = self.get_requested_mode(request.POST.get("mode"))
        if requested_mode == "verified" and request.POST.get("honor-code"):
            requested_mode = "honor"

        allowed_modes = CourseMode.modes_for_course_dict(course_id)
        if requested_mode not in allowed_modes:
            return HttpResponseBadRequest(_("Enrollment mode not supported"))

        if requested_mode in ("audit", "honor"):
            CourseEnrollment.enroll(user, course_id, requested_mode)
            return redirect('dashboard')

        mode_info = allowed_modes[requested_mode]

        if requested_mode == "verified":
            amount = request.POST.get("contribution") or \
                request.POST.get("contribution-other-amt") or 0

            try:
                # validate the amount passed in and force it into two digits
                amount_value = decimal.Decimal(amount).quantize(decimal.Decimal('.01'), rounding=decimal.ROUND_DOWN)
            except decimal.InvalidOperation:
                error_msg = _("Invalid amount selected.")
                return self.get(request, course_id, error=error_msg)

            # Check for minimum pricing
            if amount_value < mode_info.min_price:
                error_msg = _("No selected price or selected price is too low.")
                return self.get(request, course_id, error=error_msg)

            donation_for_course = request.session.get("donation_for_course", {})
            donation_for_course[course_id] = amount_value
            request.session["donation_for_course"] = donation_for_course
            if SoftwareSecurePhotoVerification.user_has_valid_or_pending(request.user):
                return redirect(
                    reverse('verify_student_verified',
                            kwargs={'course_id': course_id}) + "?upgrade={}".format(upgrade)
                )

            return redirect(
                reverse('verify_student_show_requirements',
                        kwargs={'course_id': course_id}) + "?upgrade={}".format(upgrade))
开发者ID:Gfirey,项目名称:edx-platform,代码行数:55,代码来源:views.py


示例12: piazza_discussion

def piazza_discussion(request, course_id):
    '''
    Shows the page under the Discussion tab with an iframe containing Piazza
    '''
    # Create a new tool configuration
    config = ToolConfig(title = 'Piazza',
            launch_url = LTI_LAUNCH_URL)

    # Create tool consumer using LTI!
    consumer = ToolConsumer(LTI_CONSUMER_KEY,
            LTI_CONSUMER_SECRET)
    consumer.set_config(config)

    
    #retrieve user and course models
    user = User.objects.prefetch_related("groups").get(id=request.user.id)
    userProfile = UserProfile.objects.get(user_id=user.id)
    course = course_from_id(course_id)

    #check for permissions to determine what role to pass to Piazza.com through 
    piazza_role = ''
    if user.groups.filter(name=('instructor_'+course_id)).count() != 0 or request.user.is_staff:
        piazza_role = 'Instructor'
    elif user.groups.filter(name=('staff_'+course_id)).count() != 0:
        piazza_role = 'Staff'
    else:
        piazza_role = 'Learner'

    # Set some launch data from: http://www.imsglobal.org/LTI/v1p1pd/ltiIMGv1p1pd.html#_Toc309649684
    consumer.resource_link_id = course_id
    consumer.lis_person_contact_email_primary = user.email
    consumer.lis_person_name_full = str(userProfile.name)
    hash = hashlib.md5()
    hash.update(str(userProfile.user_id))
    consumer.user_id = hash.hexdigest()

    #TODO: check if user is is_staff, student, professor, or staff and set the role appropriately
    consumer.roles = piazza_role
    consumer.context_id = course_id
    consumer.context_title = course.display_name_with_default
    consumer.context_label = course.number.replace('_', ' ')
    consumer.tool_consumer_instance_guid = 'lms.cvn.columbia.edu'
    consumer.tool_consumer_instance_description = 'Columbia University'
 

    launch_data = consumer.generate_launch_data()
    launch_url = consumer.launch_url


    course = get_course_with_access(request.user, course_id, 'load')
    staff_access = has_access(request.user, course, 'staff')
    masq = setup_masquerade(request, staff_access)    # allow staff to toggle masquerade on info page

    return render_to_response('courseware/piazza_discussion.html', {'request': request, 'course_id': course_id, 'cache': None,
            'course': course, 'staff_access': staff_access, 'masquerade': masq, 'launch_url':launch_url, 'launch_data':launch_data})
开发者ID:mjg2203,项目名称:edx-platform-seas,代码行数:55,代码来源:views.py


示例13: drop_enroll_courses

def drop_enroll_courses(request):
    r = list()
    user = User.objects.get(id=request.GET.get('user_id'))
    for enrollment in CourseEnrollment.enrollments_for_user(user):
        try:
            course = course_from_id(enrollment.course_id)
            r.append({"id": course.id, "name": str(course.display_coursenumber) + ' ' + course.display_name})
        except ItemNotFoundError:
            log.error("User {0} enrolled in non-existent course {1}".format(user.username, enrollment.course_id))
    r.sort(key=lambda x: x['name'], reverse=False)
    return HttpResponse(json.dumps(r), content_type="application/json")
开发者ID:EduPepperPDTesting,项目名称:pepper2013-testing,代码行数:11,代码来源:time_report.py


示例14: get

    def get(self, request, course_id, error=None):
        if CourseEnrollment.enrollment_mode_for_user(request.user, course_id) == 'pay_with_coupon':
            return redirect(reverse('dashboard'))
        price = get_base_price_for_course_id(course_id)

        context = {
            "course_id": course_id,
            "price": price,
            "course_name": course_from_id(course_id).display_name,
            "error": error,
        }
        return render_to_response("coupons/pay_with_coupon.html", context)
开发者ID:idefs,项目名称:edx-platform,代码行数:12,代码来源:views.py


示例15: show_requirements

def show_requirements(request, course_id):
    """
    Show the requirements necessary for
    """
    if CourseEnrollment.enrollment_mode_for_user(request.user, course_id) == 'verified':
        return redirect(reverse('dashboard'))
    context = {
        "course_id": course_id,
        "is_not_active": not request.user.is_active,
        "course_name": course_from_id(course_id).display_name,
    }
    return render_to_response("verify_student/show_requirements.html", context)
开发者ID:AzizYosofi,项目名称:edx-platform,代码行数:12,代码来源:views.py


示例16: piazza_test

def piazza_test(request, course_id):
    # Create a new tool configuration
    config = ToolConfig(title = 'Piazza',
            launch_url = LTI_LAUNCH_URL)

    # Create tool consumer using LTI!
    consumer = ToolConsumer(LTI_CONSUMER_KEY,
            LTI_CONSUMER_SECRET)
    consumer.set_config(config)

    #retrieve user and course models
    user = User.objects.prefetch_related("groups").get(id=request.user.id)
    userProfile = UserProfile.objects.get(user_id=user.id)
    course = course_from_id(course_id)

    #check for permissions to determine what role to pass to Piazza.com through 
    piazza_role = ''
    if user.groups.filter(name=('instructor_'+course_id)).count() != 0 or request.user.is_staff:
        piazza_role = 'Instructor'
    elif user.groups.filter(name=('staff_'+course_id)).count() != 0:
        piazza_role = 'Staff'
    else:
        piazza_role = 'Learner'

    # Set some launch data from: http://www.imsglobal.org/LTI/v1p1pd/ltiIMGv1p1pd.html#_Toc309649684
    consumer.resource_link_id = course_id
    consumer.lis_person_contact_email_primary = user.email
    consumer.lis_person_name_full = str(userProfile.name)
    hash = hashlib.md5()
    hash.update(str(userProfile.user_id))
    consumer.user_id = hash.hexdigest()
    #TODO: check if user is is_staff, student, professor, or staff and set the role appropriately
    #consumer.roles = 'Learner'
    consumer.roles = piazza_role
    consumer.context_id = course_id
    consumer.context_title = course.display_name_with_default
    consumer.context_label = course.number.replace('_', ' ')
    consumer.tool_consumer_instance_guid = 'lms.cvn.columbia.edu'
    consumer.tool_consumer_instance_description = 'Columbia University'

    launch_data = consumer.generate_launch_data()
    launch_url = consumer.launch_url

    #render a self-submitting form that sends all data to Piazza.com via the LTI standard
    returnable = '<form id="ltiLaunchFormSubmitArea" action="' + launch_url + '" name="ltiLaunchForm" id="ltiLaunchForm" method="post" encType="application/x-www-form-urlencoded">'
    for key in launch_data:
        returnable += '<input type="hidden" name="'+ key +'" value="'+ str(launch_data[key]) + '"/>'
    returnable += '<input type="submit" value="Go to Piazza"></input>'
    returnable += '</form>'
    returnable += '<script language="javascript">document.getElementById("ltiLaunchFormSubmitArea").style.display = "none";document.ltiLaunchForm.submit();</script>'
    return HttpResponse(returnable)
开发者ID:mjg2203,项目名称:edx-platform-seas,代码行数:51,代码来源:views.py


示例17: fetch_reverify_banner_info

def fetch_reverify_banner_info(request, course_id):
    """
    Fetches needed context variable to display reverification banner in courseware
    """
    reverifications = defaultdict(list)
    user = request.user
    if not user.id:
        return reverifications
    enrollment = CourseEnrollment.get_or_create_enrollment(request.user, course_id)
    course = course_from_id(course_id)
    info = single_course_reverification_info(user, course, enrollment)
    if info:
        reverifications[info.status].append(info)
    return reverifications
开发者ID:Neodemia,项目名称:edx-platform,代码行数:14,代码来源:views.py


示例18: tnl_table_data

def tnl_table_data():
    """
    Returns the data needed to build the tables on the config page
    """
    # Get the Domains.
    domains = tnl_get_domain()
    # Get the districts.
    districts = tnl_get_district()
    # Get the list of course ids.
    courses = tnl_get_course()
    # Load the courses and add the name to the objects.
    for x in range(0, len(courses)):
        course = course_from_id(courses[x].course)
        courses[x].name = course.display_name_with_default
    return domains, districts, courses
开发者ID:EduPepperPDTesting,项目名称:pepper2013-testing,代码行数:15,代码来源:views.py


示例19: single_item_receipt_context

 def single_item_receipt_context(self):
     course = course_from_id(self.course_id)
     return {
         "course_id": self.course_id,
         "course_name": course.display_name_with_default,
         "course_org": course.display_org_with_default,
         "course_num": course.display_number_with_default,
         "course_start_date_text": course.start_date_text,
         "course_has_started": course.start > datetime.today().replace(tzinfo=pytz.utc),
         "course_root_url": reverse(
             'course_root',
             kwargs={'course_id': self.course_id.to_deprecated_string()}  # pylint: disable=no-member
         ),
         "dashboard_url": reverse('dashboard'),
     }
开发者ID:Bvic,项目名称:edx-platform,代码行数:15,代码来源:models.py


示例20: add_to_order

    def add_to_order(cls, order, course_id, cost, mode, currency='usd'):
        """
        Add a CertificateItem to an order

        Returns the CertificateItem object after saving

        `order` - an order that this item should be added to, generally the cart order
        `course_id` - the course that we would like to purchase as a CertificateItem
        `cost` - the amount the user will be paying for this CertificateItem
        `mode` - the course mode that this certificate is going to be issued for

        This item also creates a new enrollment if none exists for this user and this course.

        Example Usage:
            cart = Order.get_cart_for_user(user)
            CertificateItem.add_to_order(cart, 'edX/Test101/2013_Fall', 30, 'verified')

        """
        super(CertificateItem, cls).add_to_order(order, course_id, cost, currency=currency)
        try:
            course_enrollment = CourseEnrollment.objects.get(user=order.user, course_id=course_id)
        except ObjectDoesNotExist:
            course_enrollment = CourseEnrollment.create_enrollment(order.user, course_id, mode=mode)

        # do some validation on the enrollment mode
        valid_modes = CourseMode.modes_for_course_dict(course_id)
        if mode in valid_modes:
            mode_info = valid_modes[mode]
        else:
            raise InvalidCartItem(_("Mode {mode} does not exist for {course_id}").format(mode=mode, course_id=course_id))
        item, _created = cls.objects.get_or_create(
            order=order,
            user=order.user,
            course_id=course_id,
            course_enrollment=course_enrollment,
            mode=mode
        )
        item.status = order.status
        item.qty = 1
        item.unit_cost = cost
        course_name = course_from_id(course_id).display_name
        item.line_desc = _("Certificate of Achievement, {mode_name} for course {course}").format(mode_name=mode_info.name,
                                                                                                 course=course_name)
        item.currency = currency
        order.currency = currency
        order.save()
        item.save()
        return item
开发者ID:felipemontoya,项目名称:edx-platform,代码行数:48,代码来源:models.py



注:本文中的student.views.course_from_id函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python views.create_account函数代码示例发布时间:2022-05-27
下一篇:
Python views.confirm_email_change函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap