Exemple #1
0
def upload(request):
    course_prefix = request.POST.get("course_prefix")
    course_suffix = request.POST.get("course_suffix")
    common_page_data = get_common_page_data(request, course_prefix, course_suffix)

    if request.method == "POST":
        form = FileUploadForm(request.POST, request.FILES, course=common_page_data['course'])
        if form.is_valid():
            new_file = form.save(commit=False)
            new_file.course = common_page_data['course']
            new_file.index = new_file.section.getNextIndex()
            new_file.mode = 'draft'
            new_file.handle = course_prefix + "--" + course_suffix

            new_file.save()
            new_file.create_ready_instance()

            parent_type = request.POST.get('parent')
            if parent_type and parent_type[:4] != 'none':
                parent_type, parent_id = parent_type.split(',')
            else:
                parent_type, parent_id = None, None
            if parent_type:
                parent_ref = ContentGroup.groupable_types[parent_type].objects.get(id=long(parent_id)).image
                content_group_groupid = ContentGroup.add_parent(new_file.image.course, parent_type, parent_ref.image)
                ContentGroup.add_child(content_group_groupid, 'file', new_file.image, display_style=request.POST.get('display_style'))

            return redirect('courses.views.course_materials', course_prefix, course_suffix)
    else:
        form = FileUploadForm(course=common_page_data['course'])

    return render(request, 'files/upload.html',
            {'common_page_data': common_page_data,
             'form': form,
             })
Exemple #2
0
def edit(request):
    course_prefix = request.POST.get("course_prefix")
    course_suffix = request.POST.get("course_suffix")
    file_id = request.POST.get("file_id", "-1")
    common_page_data = get_common_page_data(request, course_prefix, course_suffix)
    try:
        file = File.objects.get(id=int(file_id), course=common_page_data["draft_course"])
    except File.DoesNotExist:
        raise Http404

    if request.method == "POST":
        form = FileEditForm(request.POST, course=common_page_data["draft_course"], instance=file)
        if form.is_valid():
            form.save()
            file.commit()

            parent_type = request.POST.get("parent")
            if parent_type and parent_type[:4] != "none":
                parent_type, parent_id = parent_type.split(",")
            else:
                parent_type, parent_id = None, None
            if parent_type:
                parent_ref = ContentGroup.groupable_types[parent_type].objects.get(id=long(parent_id))
                content_group_groupid = ContentGroup.add_parent(file.image.course, parent_type, parent_ref.image)
                ContentGroup.add_child(
                    content_group_groupid, "file", file.image, display_style=request.POST.get("display_style", "list")
                )
            else:  # file should have no parents, so delete its place in a contentgroup if it's a child
                try:
                    cgobj = file.image.contentgroup_set.get()
                    if cgobj.level != 1:
                        cgobj.delete()
                except ContentGroup.DoesNotExist:  # nothing to do if the file is not in a contentgroup
                    pass
            return redirect("courses.views.course_materials", course_prefix, course_suffix)
    else:
        form = FileEditForm(instance=file, course=common_page_data["course"])

    reverseview = "courses.files.actions.edit"
    cg_info = ContentGroup.groupinfo_by_id("file", file.image.id)
    parent = cg_info.get("__parent", None)
    if not parent:
        parent_val = "none,none"
    else:
        parent_val = "%s,%d" % (cg_info["__parent_tag"], parent.image.id)

    return render(
        request,
        "files/upload.html",
        {
            "file": file,
            "parent_val": parent_val,
            "reverseview": reverseview,
            "common_page_data": common_page_data,
            "form": form,
        },
    )
Exemple #3
0
def edit(request):
    course_prefix = request.POST.get("course_prefix")
    course_suffix = request.POST.get("course_suffix")
    file_id = request.POST.get("file_id","-1")
    common_page_data = get_common_page_data(request, course_prefix, course_suffix)
    try:
        file=File.objects.get(id=int(file_id), course=common_page_data['draft_course'])
    except File.DoesNotExist:
        raise Http404

    if request.method == "POST":
        form = FileEditForm(request.POST, course=common_page_data['draft_course'], instance=file)
        if form.is_valid():
            form.save()
            file.commit()
            
            parent_type = request.POST.get('parent')
            if parent_type and parent_type[:4] != 'none':
                parent_type, parent_id = parent_type.split(',')
            else:
                parent_type, parent_id = None, None
            if parent_type:
                parent_ref = ContentGroup.groupable_types[parent_type].objects.get(id=long(parent_id))
                if parent_ref != file:
                    # Don't bother updating the ContentGroup if self this is already the parent of the group
                    # (which is implicitly the case for all non-grouped items)
                    content_group_groupid = ContentGroup.add_parent(file.image.course, parent_type, parent_ref.image)
                    ContentGroup.add_child(content_group_groupid, 'file', file.image, display_style=request.POST.get('display_style','list'))
            else: #file should have no parents, so delete its place in a contentgroup if it's a child
                try:
                    cgobj = file.image.contentgroup_set.get()
                    if cgobj.level != 1:
                        cgobj.delete()
                except ContentGroup.DoesNotExist: #nothing to do if the file is not in a contentgroup
                    pass
            return redirect('courses.views.course_materials', course_prefix, course_suffix)
    else:
        form = FileEditForm(instance=file, course=common_page_data['course'])

    reverseview = 'courses.files.actions.edit'
    cg_info = ContentGroup.groupinfo_by_id('file', file.image.id)
    parent = cg_info.get('__parent', None)
    if not parent:
        parent_val = "none,none"
    else:
        parent_val = "%s,%d" % (cg_info['__parent_tag'], parent.image.id)

    return render(request, 'files/upload.html',
                  {'file':file,
                  'parent_val':parent_val,
                  'reverseview': reverseview,
                  'common_page_data': common_page_data,
                  'form': form,
                  })
Exemple #4
0
def edit(request, course_prefix, course_suffix, file_id):

    common_page_data=request.common_page_data

    try:
        file=File.objects.get(id=file_id, course=common_page_data['draft_course'])
    except File.DoesNotExist:
        raise Http404
                         
    form = FileEditForm(instance=file, course=common_page_data['draft_course'])

    reverseview = 'courses.files.actions.edit'
    cg_info = ContentGroup.groupinfo_by_id('file', file.image.id)
    parent = cg_info.get('__parent', None)
    if not parent:
        parent_val = "none,none"
    else:
        parent_val = "%s,%d" % (cg_info['__parent_tag'], parent.image.id)
    return render(request, 'files/upload.html',
            {'file':file,
             'parent_val':parent_val,
             'reverseview': reverseview,
             'common_page_data': common_page_data,
             'form': form,
             })
Exemple #5
0
def edit(request, course_prefix, course_suffix, file_id):

    common_page_data = request.common_page_data

    try:
        file = File.objects.get(id=file_id,
                                course=common_page_data['draft_course'])
    except File.DoesNotExist:
        raise Http404

    form = FileEditForm(instance=file, course=common_page_data['draft_course'])

    reverseview = 'courses.files.actions.edit'
    cg_info = ContentGroup.groupinfo_by_id('file', file.image.id)
    parent = cg_info.get('__parent', None)
    if not parent:
        parent_val = "none,none"
    else:
        parent_val = "%s,%d" % (cg_info['__parent_tag'], parent.image.id)
    return render(
        request, 'files/upload.html', {
            'file': file,
            'parent_val': parent_val,
            'reverseview': reverseview,
            'common_page_data': common_page_data,
            'form': form,
        })
Exemple #6
0
def upload(request):
    course_prefix = request.POST.get("course_prefix")
    course_suffix = request.POST.get("course_suffix")
    common_page_data = get_common_page_data(request, course_prefix,
                                            course_suffix)

    if request.method == "POST":
        form = FileUploadForm(request.POST,
                              request.FILES,
                              course=common_page_data['course'])
        if form.is_valid():
            new_file = form.save(commit=False)
            new_file.course = common_page_data['course']
            new_file.index = new_file.section.getNextIndex()
            new_file.mode = 'draft'
            new_file.handle = course_prefix + "--" + course_suffix

            new_file.save()
            new_file.create_ready_instance()

            parent_type = request.POST.get('parent')
            if parent_type and parent_type[:4] != 'none':
                parent_type, parent_id = parent_type.split(',')
            else:
                parent_type, parent_id = None, None
            if parent_type:
                parent_ref = ContentGroup.groupable_types[
                    parent_type].objects.get(id=long(parent_id)).image
                content_group_groupid = ContentGroup.add_parent(
                    new_file.image.course, parent_type, parent_ref.image)
                ContentGroup.add_child(
                    content_group_groupid,
                    'file',
                    new_file.image,
                    display_style=request.POST.get('display_style'))

            return redirect('courses.views.course_materials', course_prefix,
                            course_suffix)
    else:
        form = FileUploadForm(course=common_page_data['course'])

    return render(request, 'files/upload.html', {
        'common_page_data': common_page_data,
        'form': form,
    })
Exemple #7
0
def last_completed_record(exam, student, include_contentgroup=False):
    """Helper function to get the last completed record of this exam.
       If include_contentgroup is True, will include records from
       all of the other exams in the contentgroup.
    """
    try:
        if include_contentgroup:
            cginfo = ContentGroup.groupinfo_by_id('exam',exam.id)
            exam_list = cginfo.get('exam',[exam]) #default to a singleton list consisting of just this exam
            record = ExamRecord.objects.filter(exam__in=exam_list, complete=True, student=student).latest('last_updated')
        else:
            record = ExamRecord.objects.filter(exam=exam, complete=True, student=student).latest('last_updated')
        return record

    except ExamRecord.DoesNotExist:
        return None
Exemple #8
0
    def generate_default_quiz_formula(selfclass, course):
        """ 
            This method will return a default quiz grading formula for the course, WHICH MUST BE READY MODE.
            The default logic is: 
                * linear sum of ExamScores, except
                    * take the max of all quizzes in the same Content Group
                    * In-Video Quizzes don't count
        """
        quizzes = set(
            Exam.objects.filter(course=course,
                                exam_type='problemset',
                                invideo=False,
                                is_deleted=False,
                                live_datetime__isnull=False))
        content_groups = ContentGroup.objects.filter(course=course, level=1, exam__isnull=False,
                                                     exam__exam_type='problemset', exam__live_datetime__isnull=False) \
                                             .select_related('exam').order_by("exam__live_datetime") #top level quizzes
        parent_quizzes = map(lambda g: g.exam, content_groups)

        all_quiz_groups = []
        #add all the quizzes that are in groups first
        for parent in parent_quizzes:
            groupinfo = ContentGroup.groupinfo_by_id('exam', parent.id)
            members = groupinfo['exam']
            slugs = map(lambda i: i.slug, members)
            all_quiz_groups.append(slugs)
            quizzes = quizzes - set(members)

        #print(quizzes)
        #now add quizzes that are singletons
        for q in quizzes:
            all_quiz_groups.append([q.slug])

        #print((all_quiz_groups))
        #now just output a formula that's a linear sum of the maxes of all the groups
        def stringify_inner_list(lst):
            return "max( %s )" % " , ".join(map(lambda li: "{{%s}}" % li, lst))

        strout = " + ".join(
            map(lambda li: stringify_inner_list(li), all_quiz_groups))
        #print(strout)
        return strout
Exemple #9
0
    def generate_default_quiz_formula(selfclass, course):
        """ 
            This method will return a default quiz grading formula for the course, WHICH MUST BE READY MODE.
            The default logic is: 
                * linear sum of ExamScores, except
                    * take the max of all quizzes in the same Content Group
                    * In-Video Quizzes don't count
        """
        quizzes = set(Exam.objects.filter(course=course, exam_type='problemset', invideo=False, is_deleted=False, live_datetime__isnull=False))
        content_groups = ContentGroup.objects.filter(course=course, level=1, exam__isnull=False,
                                                     exam__exam_type='problemset', exam__live_datetime__isnull=False) \
                                             .select_related('exam').order_by("exam__live_datetime") #top level quizzes
        parent_quizzes = map(lambda g:g.exam, content_groups)

        all_quiz_groups = []
        #add all the quizzes that are in groups first
        for parent in parent_quizzes:
            groupinfo = ContentGroup.groupinfo_by_id('exam', parent.id)
            members = groupinfo['exam']
            slugs = map(lambda i: i.slug, members)
            all_quiz_groups.append(slugs)
            quizzes = quizzes-set(members)

        #print(quizzes)
        #now add quizzes that are singletons
        for q in quizzes:
            all_quiz_groups.append([q.slug])

        #print((all_quiz_groups))
        #now just output a formula that's a linear sum of the maxes of all the groups
        def stringify_inner_list(lst):
            return "max( %s )" % " , ".join(map(lambda li: "{{%s}}" % li, lst))

        strout = " + ".join(map(lambda li: stringify_inner_list(li), all_quiz_groups))
        #print(strout)
        return strout
Exemple #10
0
def save_exam_ajax(request, course_prefix, course_suffix, create_or_edit="create", old_slug=""):
    course = request.common_page_data['course']
    if course.mode == "ready":
        course = course.image
    
    slug = request.POST.get('slug','')
    title = request.POST.get('title', '')
    description = request.POST.get('description', '')
    metaXMLContent = request.POST.get('metaXMLContent', '')
    htmlContent = request.POST.get('htmlContent', '')
    xmlImported = request.POST.get('xmlImported','')
    due_date = request.POST.get('due_date', '')
    grace_period = request.POST.get('grace_period', '')
    partial_credit_deadline =  request.POST.get('partial_credit_deadline', '')
    late_penalty = request.POST.get('late_penalty', '')
    num_subs_permitted = request.POST.get('num_subs_permitted','')
    resubmission_penalty = request.POST.get('resubmission_penalty','')
    assessment_type = request.POST.get('assessment_type','')
    section=request.POST.get('section','')
    invideo_val=request.POST.get('invideo','')
    parent=request.POST.get('parent','none,none')
    
    if invideo_val and invideo_val == "true":
        invideo = True
    else:
        invideo = False

    #########Validation, lots of validation#######
    if not slug:
        return HttpResponseBadRequest("No URL identifier value provided")
    try:
        validate_slug(slug)
    except ValidationError as ve:
        return HttpResponseBadRequest(unicode(ve))

    if not title:
        return HttpResponseBadRequest("No Title value provided")
    if not metaXMLContent:
        return HttpResponseBadRequest("No metadataXML provided")
    try:
        grader = AutoGrader(metaXMLContent)
    except Exception as e: #Since this is just a validator, pass back all the exceptions
        return HttpResponseBadRequest(unicode(e))

    total_score = grader.points_possible

    if not htmlContent:
        return HttpResponseBadRequest("No Exam HTML provided")
    if not due_date:
        return HttpResponseBadRequest("No due date provided")
    if not grace_period:
        return HttpResponseBadRequest("No grace period provided")
    if not partial_credit_deadline:
        return HttpResponseBadRequest("No hard deadline provided")
    if not section:
        return HttpResponseBadRequest("Bad section provided!")

    try:
        contentsection = ContentSection.objects.get(id=section, course=course, is_deleted=False)
    except ContentSection.DoesNotExist:
        return HttpResponseBadRequest("Bad section provided!")

    dd = datetime.datetime.strptime(due_date, "%m/%d/%Y %H:%M")
    gp = datetime.datetime.strptime(grace_period, "%m/%d/%Y %H:%M")
    pcd = datetime.datetime.strptime(partial_credit_deadline, "%m/%d/%Y %H:%M")

    if assessment_type == "summative":
        autograde = True
        display_single = False
        grade_single = False
        exam_type = "problemset"
    elif assessment_type == "formative":
        autograde = True
        display_single = True
        grade_single = False #We will eventually want this to be True
        exam_type = "problemset"
    elif assessment_type == "interactive":
        autograde = True
        display_single = True
        grade_single = False
        exam_type = "interactive_exercise"
    elif assessment_type == "exam-autograde":
        autograde = True
        display_single = False
        grade_single = False
        exam_type = "exam"
    elif assessment_type == "exam-csv":
        autograde = False
        display_single = False
        grade_single = False
        exam_type = "exam"
    elif assessment_type == "survey":
        autograde = False
        display_single = False
        grade_single = False
        exam_type = "survey"
    else:
        return HttpResponseBadRequest("A bad assessment type (" + assessment_type  + ") was provided")

    if not late_penalty:
        lp = 0
    else:
        try:
            lp = int(late_penalty)
        except ValueError:
            return HttpResponseBadRequest("A non-numeric late penalty (" + late_penalty  + ") was provided")

    if not num_subs_permitted:
        sp = 999
    else:
        try:
            sp = int(num_subs_permitted)
        except ValueError:
            return HttpResponseBadRequest("A non-numeric number of submissions permitted (" + sp  + ") was provided")

    if not resubmission_penalty:
        rp = 0
    else:
        try:
            rp = int(resubmission_penalty)
        except ValueError:
            return HttpResponseBadRequest("A non-numeric resubmission penalty (" + resubmission_penalty  + ") was provided")

    if parent and parent[:4] != 'none':
        parent_type, parent = parent.split(',')
    else:
        parent_type, parent = None, None

    #create or edit the Exam
    if create_or_edit == "create":
        if Exam.objects.filter(course=course, slug=slug, is_deleted=False).exists():
            return HttpResponseBadRequest("An exam with this URL identifier already exists in this course")
        exam_obj = Exam(course=course, slug=slug, title=title, description=description, html_content=htmlContent, xml_metadata=metaXMLContent,
                        due_date=dd, assessment_type=assessment_type, mode="draft", total_score=total_score, grade_single=grade_single,
                        grace_period=gp, partial_credit_deadline=pcd, late_penalty=lp, submissions_permitted=sp, resubmission_penalty=rp,
                        exam_type=exam_type, autograde=autograde, display_single=display_single, invideo=invideo, section=contentsection,
                        xml_imported=xmlImported
                        )

        exam_obj.save()
        exam_obj.create_ready_instance()

        if parent_type:
            parent_ref = ContentGroup.groupable_types[parent_type].objects.get(id=long(parent)).image
            content_group_groupid = ContentGroup.add_parent(exam_obj.image.course, parent_type, parent_ref.image)
            ContentGroup.add_child(content_group_groupid, 'exam', exam_obj.image, display_style='list')

        return HttpResponse("Exam " + title + " created. \n" + unicode(grader))
    else:
        try: #this is nasty code, I know.  It should at least be moved into the model somehow
            exam_obj = Exam.objects.get(course=course, is_deleted=0, slug=old_slug)
            exam_obj.slug=slug
            exam_obj.title=title
            exam_obj.description=description
            exam_obj.html_content=htmlContent
            exam_obj.xml_metadata=metaXMLContent
            exam_obj.xml_imported=xmlImported
            exam_obj.due_date=dd
            exam_obj.total_score=total_score
            exam_obj.assessment_type=assessment_type
            exam_obj.grace_period=gp
            exam_obj.partial_credit_deadline=pcd
            exam_obj.late_penalty=lp
            exam_obj.submissions_permitted=sp
            exam_obj.resubmission_penalty=rp
            exam_obj.exam_type=exam_type
            exam_obj.autograde=autograde
            exam_obj.display_single=display_single
            exam_obj.grade_single=grade_single
            exam_obj.invideo=invideo
            exam_obj.section=contentsection
            exam_obj.save()
            exam_obj.commit()

            if parent_type:
                parent_ref = ContentGroup.groupable_types[parent_type].objects.get(id=long(parent)).image
                content_group_parent = parent_ref.contentgroup_set.all()
                if content_group_parent:
                    content_group_groupid = content_group_parent[0].group_id
                else:
                    content_group_groupid = ContentGroup.add_parent(exam_obj.image.course, parent_type, parent_ref.image)
                ContentGroup.add_child(content_group_groupid, 'exam', exam_obj.image, display_style='list')

            return HttpResponse("Exam " + title + " saved. \n" + unicode(grader))

        except Exam.DoesNotExist:
            return HttpResponseBadRequest("No exam exists with URL identifier %s" % old_slug)
Exemple #11
0
def save_exam_ajax(request,
                   course_prefix,
                   course_suffix,
                   create_or_edit="create",
                   old_slug=""):
    course = request.common_page_data['course']
    if course.mode == "ready":
        course = course.image

    slug = request.POST.get('slug', '')
    title = request.POST.get('title', '')
    description = request.POST.get('description', '')
    metaXMLContent = request.POST.get('metaXMLContent', '')
    htmlContent = request.POST.get('htmlContent', '')
    xmlImported = request.POST.get('xmlImported', '')
    due_date = request.POST.get('due_date', '')
    grace_period = request.POST.get('grace_period', '')
    partial_credit_deadline = request.POST.get('partial_credit_deadline', '')
    late_penalty = request.POST.get('late_penalty', '')
    num_subs_permitted = request.POST.get('num_subs_permitted', '')
    resubmission_penalty = request.POST.get('resubmission_penalty', '')
    assessment_type = request.POST.get('assessment_type', '')
    section = request.POST.get('section', '')
    invideo_val = request.POST.get('invideo', '')
    parent = request.POST.get('parent', 'none,none')

    if invideo_val and invideo_val == "true":
        invideo = True
    else:
        invideo = False

    #########Validation, lots of validation#######
    if not slug:
        return HttpResponseBadRequest("No URL identifier value provided")
    try:
        validate_slug(slug)
    except ValidationError as ve:
        return HttpResponseBadRequest(unicode(ve))

    if not title:
        return HttpResponseBadRequest("No Title value provided")
    if not metaXMLContent:
        return HttpResponseBadRequest("No metadataXML provided")
    try:
        grader = AutoGrader(metaXMLContent)
    except Exception as e:  #Since this is just a validator, pass back all the exceptions
        return HttpResponseBadRequest(unicode(e))

    total_score = grader.points_possible

    if not htmlContent:
        return HttpResponseBadRequest("No Exam HTML provided")
    if not due_date:
        return HttpResponseBadRequest("No due date provided")
    if not grace_period:
        return HttpResponseBadRequest("No grace period provided")
    if not partial_credit_deadline:
        return HttpResponseBadRequest("No hard deadline provided")
    if not section:
        return HttpResponseBadRequest("Bad section provided!")

    try:
        contentsection = ContentSection.objects.get(id=section,
                                                    course=course,
                                                    is_deleted=False)
    except ContentSection.DoesNotExist:
        return HttpResponseBadRequest("Bad section provided!")

    dd = datetime.datetime.strptime(due_date, "%m/%d/%Y %H:%M")
    gp = datetime.datetime.strptime(grace_period, "%m/%d/%Y %H:%M")
    pcd = datetime.datetime.strptime(partial_credit_deadline, "%m/%d/%Y %H:%M")

    if assessment_type == "summative":
        autograde = True
        display_single = False
        grade_single = False
        exam_type = "problemset"
    elif assessment_type == "formative":
        autograde = True
        display_single = True
        grade_single = False  #We will eventually want this to be True
        exam_type = "problemset"
    elif assessment_type == "interactive":
        autograde = True
        display_single = True
        grade_single = False
        exam_type = "interactive_exercise"
    elif assessment_type == "exam-autograde":
        autograde = True
        display_single = False
        grade_single = False
        exam_type = "exam"
    elif assessment_type == "exam-csv":
        autograde = False
        display_single = False
        grade_single = False
        exam_type = "exam"
    elif assessment_type == "survey":
        autograde = False
        display_single = False
        grade_single = False
        exam_type = "survey"
    else:
        return HttpResponseBadRequest("A bad assessment type (" +
                                      assessment_type + ") was provided")

    if not late_penalty:
        lp = 0
    else:
        try:
            lp = int(late_penalty)
        except ValueError:
            return HttpResponseBadRequest("A non-numeric late penalty (" +
                                          late_penalty + ") was provided")

    if not num_subs_permitted:
        sp = 999
    else:
        try:
            sp = int(num_subs_permitted)
        except ValueError:
            return HttpResponseBadRequest(
                "A non-numeric number of submissions permitted (" + sp +
                ") was provided")

    if not resubmission_penalty:
        rp = 0
    else:
        try:
            rp = int(resubmission_penalty)
        except ValueError:
            return HttpResponseBadRequest(
                "A non-numeric resubmission penalty (" + resubmission_penalty +
                ") was provided")

    if parent and parent[:4] != 'none':
        parent_type, parent = parent.split(',')
    else:
        parent_type, parent = None, None

    #create or edit the Exam
    if create_or_edit == "create":
        if Exam.objects.filter(course=course, slug=slug,
                               is_deleted=False).exists():
            return HttpResponseBadRequest(
                "An exam with this URL identifier already exists in this course"
            )
        exam_obj = Exam(course=course,
                        slug=slug,
                        title=title,
                        description=description,
                        html_content=htmlContent,
                        xml_metadata=metaXMLContent,
                        due_date=dd,
                        assessment_type=assessment_type,
                        mode="draft",
                        total_score=total_score,
                        grade_single=grade_single,
                        grace_period=gp,
                        partial_credit_deadline=pcd,
                        late_penalty=lp,
                        submissions_permitted=sp,
                        resubmission_penalty=rp,
                        exam_type=exam_type,
                        autograde=autograde,
                        display_single=display_single,
                        invideo=invideo,
                        section=contentsection,
                        xml_imported=xmlImported)

        exam_obj.save()
        exam_obj.create_ready_instance()

        if parent_type:
            parent_ref = ContentGroup.groupable_types[parent_type].objects.get(
                id=long(parent)).image
            content_group_groupid = ContentGroup.add_parent(
                exam_obj.image.course, parent_type, parent_ref.image)
            ContentGroup.add_child(content_group_groupid,
                                   'exam',
                                   exam_obj.image,
                                   display_style='list')

        return HttpResponse("Exam " + title + " created. \n" + unicode(grader))
    else:
        try:  #this is nasty code, I know.  It should at least be moved into the model somehow
            exam_obj = Exam.objects.get(course=course,
                                        is_deleted=0,
                                        slug=old_slug)
            exam_obj.slug = slug
            exam_obj.title = title
            exam_obj.description = description
            exam_obj.html_content = htmlContent
            exam_obj.xml_metadata = metaXMLContent
            exam_obj.xml_imported = xmlImported
            exam_obj.due_date = dd
            exam_obj.total_score = total_score
            exam_obj.assessment_type = assessment_type
            exam_obj.grace_period = gp
            exam_obj.partial_credit_deadline = pcd
            exam_obj.late_penalty = lp
            exam_obj.submissions_permitted = sp
            exam_obj.resubmission_penalty = rp
            exam_obj.exam_type = exam_type
            exam_obj.autograde = autograde
            exam_obj.display_single = display_single
            exam_obj.grade_single = grade_single
            exam_obj.invideo = invideo
            exam_obj.section = contentsection
            exam_obj.save()
            exam_obj.commit()

            if parent_type:
                parent_ref = ContentGroup.groupable_types[
                    parent_type].objects.get(id=long(parent)).image
                content_group_parent = parent_ref.contentgroup_set.all()
                if content_group_parent:
                    content_group_groupid = content_group_parent[0].group_id
                else:
                    content_group_groupid = ContentGroup.add_parent(
                        exam_obj.image.course, parent_type, parent_ref.image)
                ContentGroup.add_child(content_group_groupid,
                                       'exam',
                                       exam_obj.image,
                                       display_style='list')

            return HttpResponse("Exam " + title + " saved. \n" +
                                unicode(grader))

        except Exam.DoesNotExist:
            return HttpResponseBadRequest(
                "No exam exists with URL identifier %s" % old_slug)
Exemple #12
0
def edit(request):
    course_prefix = request.POST.get("course_prefix")
    course_suffix = request.POST.get("course_suffix")
    file_id = request.POST.get("file_id", "-1")
    common_page_data = get_common_page_data(request, course_prefix,
                                            course_suffix)
    try:
        file = File.objects.get(id=int(file_id),
                                course=common_page_data['draft_course'])
    except File.DoesNotExist:
        raise Http404

    if request.method == "POST":
        form = FileEditForm(request.POST,
                            course=common_page_data['draft_course'],
                            instance=file)
        if form.is_valid():
            form.save()
            file.commit()

            parent_type = request.POST.get('parent')
            if parent_type and parent_type[:4] != 'none':
                parent_type, parent_id = parent_type.split(',')
            else:
                parent_type, parent_id = None, None
            if parent_type:
                parent_ref = ContentGroup.groupable_types[
                    parent_type].objects.get(id=long(parent_id))
                if parent_ref != file:
                    # Don't bother updating the ContentGroup if self this is already the parent of the group
                    # (which is implicitly the case for all non-grouped items)
                    content_group_groupid = ContentGroup.add_parent(
                        file.image.course, parent_type, parent_ref.image)
                    ContentGroup.add_child(content_group_groupid,
                                           'file',
                                           file.image,
                                           display_style=request.POST.get(
                                               'display_style', 'list'))
            else:  #file should have no parents, so delete its place in a contentgroup if it's a child
                try:
                    cgobj = file.image.contentgroup_set.get()
                    if cgobj.level != 1:
                        cgobj.delete()
                except ContentGroup.DoesNotExist:  #nothing to do if the file is not in a contentgroup
                    pass
            return redirect('courses.views.course_materials', course_prefix,
                            course_suffix)
    else:
        form = FileEditForm(instance=file, course=common_page_data['course'])

    reverseview = 'courses.files.actions.edit'
    cg_info = ContentGroup.groupinfo_by_id('file', file.image.id)
    parent = cg_info.get('__parent', None)
    if not parent:
        parent_val = "none,none"
    else:
        parent_val = "%s,%d" % (cg_info['__parent_tag'], parent.image.id)

    return render(
        request, 'files/upload.html', {
            'file': file,
            'parent_val': parent_val,
            'reverseview': reverseview,
            'common_page_data': common_page_data,
            'form': form,
        })