Пример #1
0
def flush_tokens(request, level, semester, course):
    """View for flushing/deleleting selected tokens.

    Checks that the user has necessary permissions and then deletes matched
    course's exam tokens."""

    if not can_add_question(request):
        messages.warning(
            request, 'You lack necessary permissions to flush course tokens.')
        return redirect('index')

    try:
        flushed = 0
        tokens = get_list_or_404(Token,
                                 level=int(level),
                                 semester=int(semester),
                                 course=int(course))
        course = f"{tokens[0].course.title} ({str(tokens[0].course.code)})"
        for t in tokens:
            t.delete()
            flushed += 1
    except Exception:
        flushed = 0
        course = "Selected Course"

    messages.success(
        request, f"""
        {flushed} token(s) for <strong>{course}</strong> Flushed/Deleted
        successfully.
    """)
    return redirect('index')
Пример #2
0
def mark_scripts(request, course):
    """Marks students' answer scripts of the selected course.

    Checks if the user user has necessary permissions.
    Else, returns appropriate message and redirects to Home Page."""

    # Check that user can mark scripts.
    if not can_add_question(request):
        messages.warning(
            request, "You lack the necessary permissions to mark script(s).")
        return redirect('index')

    # Capture the answers from database and create necessary variables.
    answers = get_list_or_404(Answer, course=course)
    score = 0  # Holds total score of all students.
    user_score = {}  # Holds each student and respective total score.

    # Loop through the answers and mark the script of each user.
    for a in answers:
        if a.user_answer == a.question.answer:  # Is user choice correct?
            a.is_answer = True  # Then mark it correct.
            a.save()  # And save.
            score += a.question.score  # Update overall total score.
            # Update user score in the dict.
            if a.answered_by in user_score:
                user_score[a.answered_by] += a.question.score
            # Or add user to dict with corresponding score.
            else:
                user_score[a.answered_by] = a.question.score

    if user_score:
        # Loop through the course results dict.
        for u, v in user_score.items():
            # And create user result for each result marked.
            CourseResult.objects.get_or_create(user=u,
                                               course=answers[0].course,
                                               level=answers[0].level,
                                               semester=answers[0].semester,
                                               score=v,
                                               grade=grade(v))

        cr = CourseResult.objects.filter(course=answers[0].course,
                                         level=answers[0].level,
                                         semester=answers[0].semester)
        return render(request,
                      'cbt/marked_scripts.html',
                      context={
                          'ans': cr[0],
                          'score': score,
                          'cr': cr
                      })

    messages.info(
        request, "No results were marked. Ensure the students have taken"
        " their exams and try again.")
    return redirect('mark_script')
Пример #3
0
def compile_results(request, level, semester):
    """Compiles selected semester and level results for all students.

    Loops through all the course results and compiles the results for that
    semester and level.

    Renders the result in the template."""

    # Check that user can mark scripts.
    if not can_add_question(request):
        messages.warning(
            request, "You lack necessary permissions to compile results(s).")
        return redirect('index')

    # Get all results for the level and semester.
    results = get_list_or_404(CourseResult, level=level, semester=semester)
    c_rs = {}
    # Compile the results.
    for result in results:
        # If the result has being added, update the record.
        if result.user in c_rs:
            c_rs[result.user][0] += 1
            c_rs[result.user][1] += result.score
            c_rs[result.user][2] += result.course.unit
            c_rs[result.user][3] += result.course.unit * grade(result.score,
                                                               int_grade=True)
        # Else, add to record.
        else:
            c_rs[result.user] = [
                1, result.score, result.course.unit,
                result.course.unit * grade(result.score, int_grade=True)
            ]

    # Save compiled results to database
    for k, v in c_rs.items():
        Result.objects.get_or_create(user=k,
                                     level=level,
                                     semester=semester,
                                     total_score=v[1],
                                     total_courses=v[0],
                                     total_units=v[2],
                                     gpa=v[3] / v[2])

    # Get result for display in template.
    c_results = get_list_or_404(Result, level=level, semester=semester)
    return render(request,
                  'cbt/compiled_result.html',
                  context={
                      'results': c_results,
                      'level': c_results[0].get_level_display(),
                      'semester': c_results[0].get_semester_display()
                  })
Пример #4
0
def gen_token(request):
    """View for generating tokens for examinations.

    Examination tokens will be generated for every user that has registered
    the given course.

    Redirects to tokens view page on form valid."""

    # Check that user can generate examination tokens.
    if not can_add_question(request):
        messages.warning(
            request, 'You lack necessary permissions to generate token(s).')
        return redirect('index')

    if request.method == "POST":
        form = GenerateTokenForm(request.POST)
        if form.is_valid():
            data = form.cleaned_data
            users = UserCourse.objects.filter(level=int(data["level"]),
                                              semester=int(data["semester"]),
                                              course=data["course"])
            for u in users:
                Token.objects.create(user=u.user,
                                     token=token(),
                                     level=int(data['level']),
                                     semester=int(data['semester']),
                                     course=data['course'])
            messages.success(request,
                             'Examination tokens generated successfully.')
            return redirect('tokens',
                            level=int(data['level']),
                            semester=int(data['semester']),
                            course=int(data['course'].id))
    else:
        form = GenerateTokenForm()

    return render(request,
                  'cbt/generic_form.html',
                  context={
                      'form':
                      form,
                      'title_text':
                      'Select Course To Generate Tokens For',
                      'detail_text':
                      '''Please select the <strong>Level/Session</strong>,
        <strong>Semester</strong> and <strong>Course</strong> you want to
        generate Tokens for and then click <strong class="text-success">
        Proceed</strong>.'''
                  })
Пример #5
0
def add_question(request, course, total):
    """View for adding question(s) for selected course."""

    if not can_add_question(request):
        messages.warning(
            request, "You lack the necessary permissions to add question(s).")
        return redirect('index')

    course = get_object_or_404(Course, pk=course)
    question_form_set = modelformset_factory(
        Question,
        exclude=['course', 'semester', 'level'],
        extra=total,
        max_num=30)
    if request.method == 'POST':
        formset = question_form_set(request.POST)
        if formset.is_valid():
            # Check if any of the question forms was modified.
            if formset.has_changed():
                # Capture the total number of questions
                t_f = formset.total_form_count()
                # Go through all the questions and set necessary fields.
                while t_f:
                    formset[t_f - 1].instance.course = course
                    formset[t_f - 1].instance.level = course.level
                    formset[t_f - 1].instance.semester = course.semester
                    t_f -= 1

                saved = len(formset.save())
                messages.success(request,
                                 f'{saved} Questions added successfully.')
                return redirect('index')
            messages.info(
                request, "You didn't change any of the questions form. "
                "Hence, No questions was added.")
        else:
            messages.warning(
                request, "Some invalid details discovered. Please correct"
                " accordingly below.")

    else:
        formset = question_form_set(queryset=Question.objects.none())

    return render(request, "cbt/add_question.html", {
        "formset": formset,
        "course": course
    })
Пример #6
0
def tokens(request, level, semester, course):
    """View for retrieving and displaying generated token(s).

    Displays matched course tokens if the user has necessary permissions."""

    if not can_add_question(request):
        messages.warning(
            request, 'You lack necessary permissions to access course tokens')
        return redirect('index')

    u_tokens = get_list_or_404(Token,
                               level=level,
                               semester=semester,
                               course=course)
    return render(request,
                  'cbt/token.html',
                  context={
                      'u_tokens': u_tokens,
                      'level': u_tokens[0].get_level_display(),
                      'semester': u_tokens[0].get_semester_display()
                  })