-
Notifications
You must be signed in to change notification settings - Fork 226
/
Copy pathviews.py
4259 lines (3850 loc) · 161 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import csv
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
from django.contrib.auth import login, logout, authenticate
from django.shortcuts import render, get_object_or_404, redirect
from django.template import Context, Template, loader
from django.http import Http404
from django.db.models import Max, Q, F
from django.db import models
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from django.contrib.contenttypes.models import ContentType
from django.forms.models import inlineformset_factory
from django.forms import fields
from django.utils import timezone
from django.core.exceptions import (
MultipleObjectsReturned, ObjectDoesNotExist
)
import datetime
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib import messages
from taggit.models import Tag
from django.urls import reverse
from django.conf import settings
import json
import numpy as np
from textwrap import dedent
import zipfile
import markdown
import ruamel
import pandas as pd
try:
from StringIO import StringIO as string_io
except ImportError:
from io import BytesIO as string_io
import re
# Local imports.
from online_test.celery_settings import app
from yaksh.code_server import get_result as get_result_from_code_server
from yaksh.models import (
Answer, AnswerPaper, AssignmentUpload, Course, FileUpload, FloatTestCase,
HookTestCase, IntegerTestCase, McqTestCase, Profile,
QuestionPaper, QuestionSet, Quiz, Question, StandardTestCase,
StdIOBasedTestCase, StringTestCase, TestCase, User,
get_model_class, FIXTURES_DIR_PATH, MOD_GROUP_NAME, Lesson, LessonFile,
LearningUnit, LearningModule, CourseStatus, question_types, Post, Comment,
Topic, TableOfContents, LessonQuizAnswer, MicroManager, QRcode,
QRcodeHandler, dict_to_yaml
)
from stats.models import TrackLesson
from yaksh.forms import (
UserRegisterForm, UserLoginForm, QuizForm, QuestionForm,
QuestionFilterForm, CourseForm, ProfileForm,
UploadFileForm, FileForm, QuestionPaperForm, LessonForm,
LessonFileForm, LearningModuleForm, ExerciseForm, TestcaseForm,
SearchFilterForm, PostForm, CommentForm, TopicForm, VideoQuizForm
)
from yaksh.settings import SERVER_POOL_PORT, SERVER_HOST_NAME
from .settings import URL_ROOT
from .file_utils import extract_files, is_csv
from .send_emails import (send_user_mail,
generate_activation_key, send_bulk_mail)
from .decorators import email_verified, has_profile
from .tasks import regrade_papers, update_user_marks
from notifications_plugin.models import Notification
import hashlib
def my_redirect(url):
"""An overridden redirect to deal with URL_ROOT-ing. See settings.py
for details."""
return redirect(URL_ROOT + url)
def my_render_to_response(request, template, context=None, **kwargs):
"""Overridden render_to_response.
"""
if context is None:
context = {'URL_ROOT': URL_ROOT}
else:
context['URL_ROOT'] = URL_ROOT
return render(request, template, context, **kwargs)
def is_moderator(user, group_name=MOD_GROUP_NAME):
"""Check if the user is having moderator rights"""
try:
group = Group.objects.get(name=group_name)
return (
user.profile.is_moderator and
group.user_set.filter(id=user.id).exists()
)
except Profile.DoesNotExist:
return False
except Group.DoesNotExist:
return False
def add_as_moderator(users, group_name=MOD_GROUP_NAME):
""" add users to moderator group """
try:
Group.objects.get(name=group_name)
except Group.DoesNotExist:
raise Http404('The Group {0} does not exist.'.format(group_name))
for user in users:
if not is_moderator(user):
user.profile.is_moderator = True
user.profile.save()
def get_html_text(md_text):
"""Takes markdown text and converts it to html"""
return markdown.markdown(
md_text, extensions=['tables', 'fenced_code']
)
def formfield_callback(field):
if (isinstance(field, models.TextField) and field.name == 'expected_input'):
return fields.CharField(strip=False, required = False)
if (isinstance(field, models.TextField) and field.name == 'expected_output'):
return fields.CharField(strip=False)
return field.formfield()
@email_verified
def index(request, next_url=None):
"""The start page.
"""
user = request.user
if user.is_authenticated:
if is_moderator(user):
return my_redirect('/exam/manage/' if not next_url else next_url)
return my_redirect("/exam/quizzes/" if not next_url else next_url)
return my_redirect("/exam/login/")
def user_register(request):
""" Register a new user.
Create a user and corresponding profile and store roll_number also."""
user = request.user
if user.is_authenticated:
return my_redirect("/exam/quizzes/")
context = {}
if request.method == "POST":
form = UserRegisterForm(request.POST)
if form.is_valid():
u_name, pwd, user_email, key = form.save()
new_user = authenticate(username=u_name, password=pwd)
login(request, new_user)
if user_email and key:
success, msg = send_user_mail(user_email, key)
context = {'activation_msg': msg}
return my_render_to_response(
request,
'yaksh/activation_status.html', context
)
return index(request)
else:
return my_render_to_response(
request, 'yaksh/register.html', {'form': form}
)
else:
form = UserRegisterForm()
return my_render_to_response(
request, 'yaksh/register.html', {'form': form}
)
def user_logout(request):
"""Show a page to inform user that the quiz has been compeleted."""
logout(request)
context = {'message': "You have been logged out successfully"}
return my_render_to_response(request, 'yaksh/complete.html', context)
@login_required
@has_profile
@email_verified
def quizlist_user(request, enrolled=None, msg=None):
"""Show All Quizzes that is available to logged-in user."""
user = request.user
courses_data = []
if request.method == "POST":
course_code = request.POST.get('course_code')
hidden_courses = Course.objects.get_hidden_courses(code=course_code)
courses = hidden_courses
title = 'Search Results'
else:
enrolled_courses = user.students.filter(is_trial=False).order_by('-id')
remaining_courses = list(Course.objects.filter(
active=True, is_trial=False, hidden=False
).exclude(
id__in=enrolled_courses.values_list("id", flat=True)
).order_by('-id'))
courses = list(enrolled_courses)
courses.extend(remaining_courses)
title = 'All Courses'
for course in courses:
if course.students.filter(id=user.id).exists():
_percent = course.get_completion_percent(user)
else:
_percent = None
courses_data.append(
{
'data': course,
'completion_percentage': _percent,
}
)
messages.info(request, msg)
context = {
'user': user, 'courses': courses_data,
'title': title
}
return my_render_to_response(request, "yaksh/quizzes_user.html", context)
@login_required
@email_verified
def results_user(request):
"""Show list of Results of Quizzes that is taken by logged-in user."""
user = request.user
papers = AnswerPaper.objects.get_user_answerpapers(user)
context = {'papers': papers}
return my_render_to_response(request, "yaksh/results_user.html", context)
@login_required
@email_verified
def add_question(request, question_id=None):
user = request.user
if not is_moderator(user):
raise Http404('You are not allowed to view this page !')
test_case_type = None
if question_id is not None:
question = Question.objects.get(id=question_id)
uploaded_files = FileUpload.objects.filter(question_id=question.id)
else:
question = None
uploaded_files = []
if request.method == 'POST':
qform = QuestionForm(request.POST, instance=question)
fileform = FileForm(request.POST, request.FILES)
remove_files_id = request.POST.getlist('clear')
added_files = request.FILES.getlist('file_field')
extract_files_id = request.POST.getlist('extract')
hide_files_id = request.POST.getlist('hide')
if remove_files_id:
files = FileUpload.objects.filter(id__in=remove_files_id).delete()
if extract_files_id:
files = FileUpload.objects.filter(id__in=extract_files_id)
for file in files:
file.set_extract_status()
if hide_files_id:
files = FileUpload.objects.filter(id__in=hide_files_id)
for file in files:
file.toggle_hide_status()
formsets = []
for testcase in TestCase.__subclasses__():
formset = inlineformset_factory(
Question, testcase, extra=0,
fields='__all__',
form=TestcaseForm,
formfield_callback=formfield_callback
)
formsets.append(formset(
request.POST, request.FILES, instance=question
)
)
if qform.is_valid():
question = qform.save(commit=False)
question.user = user
question.save()
# many-to-many field save function used to save the tags
if added_files:
for file in added_files:
FileUpload.objects.get_or_create(
question=question, file=file
)
qform.save_m2m()
for formset in formsets:
if formset.is_valid():
formset.save()
test_case_type = request.POST.get('case_type', None)
uploaded_files = FileUpload.objects.filter(question_id=question.id)
messages.success(request, "Question saved successfully")
else:
context = {
'qform': qform,
'fileform': fileform,
'question': question,
'formsets': formsets,
'uploaded_files': uploaded_files
}
messages.warning(request, "Unable to save the question")
return render(request, "yaksh/add_question.html", context)
qform = QuestionForm(instance=question)
fileform = FileForm()
formsets = []
for testcase in TestCase.__subclasses__():
if test_case_type == testcase.__name__.lower():
formset = inlineformset_factory(
Question, testcase, extra=1, fields='__all__',
form=TestcaseForm
)
else:
formset = inlineformset_factory(
Question, testcase, extra=0, fields='__all__',
form=TestcaseForm
)
formsets.append(
formset(
instance=question,
initial=[{'type': test_case_type}]
)
)
context = {'qform': qform, 'fileform': fileform, 'question': question,
'formsets': formsets, 'uploaded_files': uploaded_files}
if question is not None:
context["testcase_options"] = question.get_test_case_options()
return render(request, "yaksh/add_question.html", context)
@login_required
@email_verified
def add_quiz(request, course_id=None, module_id=None, quiz_id=None):
"""To add a new quiz in the database.
Create a new quiz and store it."""
user = request.user
if not is_moderator(user):
raise Http404('You are not allowed to view this course !')
if quiz_id:
quiz = get_object_or_404(Quiz, pk=quiz_id)
if quiz.creator != user and not course_id:
raise Http404('This quiz does not belong to you')
else:
quiz = None
if module_id:
module = get_object_or_404(LearningModule, id=module_id)
if course_id:
course = get_object_or_404(Course, pk=course_id)
if not course.is_creator(user) and not course.is_teacher(user):
raise Http404('This quiz does not belong to you')
context = {}
if request.method == "POST":
form = QuizForm(request.POST, instance=quiz)
if form.is_valid():
if quiz is None:
last_unit = module.get_learning_units().last()
order = last_unit.order + 1 if last_unit else 1
form.instance.creator = user
else:
order = module.get_unit_order("quiz", quiz)
added_quiz = form.save()
unit, created = LearningUnit.objects.get_or_create(
type="quiz", quiz=added_quiz, order=order
)
if created:
module.learning_unit.add(unit.id)
messages.success(request, "Quiz saved successfully")
return redirect(
reverse("yaksh:edit_quiz",
args=[course_id, module_id, added_quiz.id])
)
else:
form = QuizForm(instance=quiz)
context["course_id"] = course_id
context["quiz"] = quiz
context["form"] = form
return my_render_to_response(request, 'yaksh/add_quiz.html', context)
@login_required
@email_verified
def add_exercise(request, course_id=None, module_id=None, quiz_id=None):
user = request.user
if not is_moderator(user):
raise Http404('You are not allowed to view this course !')
if quiz_id:
quiz = get_object_or_404(Quiz, pk=quiz_id)
if quiz.creator != user and not course_id:
raise Http404('This quiz does not belong to you')
else:
quiz = None
if module_id:
module = get_object_or_404(LearningModule, id=module_id)
if course_id:
course = get_object_or_404(Course, pk=course_id)
if not course.is_creator(user) and not course.is_teacher(user):
raise Http404('This Course does not belong to you')
context = {}
if request.method == "POST":
form = ExerciseForm(request.POST, instance=quiz)
if form.is_valid():
if quiz is None:
last_unit = module.get_learning_units().last()
order = last_unit.order + 1 if last_unit else 1
form.instance.creator = user
else:
order = module.get_unit_order("quiz", quiz)
quiz = form.save(commit=False)
quiz.is_exercise = True
quiz.time_between_attempts = 0
quiz.weightage = 0
quiz.allow_skip = False
quiz.attempts_allowed = -1
quiz.duration = 1000
quiz.pass_criteria = 0
quiz.save()
unit, created = LearningUnit.objects.get_or_create(
type="quiz", quiz=quiz, order=order
)
if created:
module.learning_unit.add(unit.id)
messages.success(
request, "{0} saved successfully".format(quiz.description)
)
return redirect(
reverse("yaksh:edit_exercise",
args=[course_id, module_id, quiz.id])
)
else:
form = ExerciseForm(instance=quiz)
context["exercise"] = quiz
context["course_id"] = course_id
context["form"] = form
return my_render_to_response(request, 'yaksh/add_exercise.html', context)
@login_required
@has_profile
@email_verified
def prof_manage(request, msg=None):
"""Take credentials of the user with professor/moderator
rights/permissions and log in."""
user = request.user
if not user.is_authenticated:
return my_redirect('/exam/login')
if not is_moderator(user):
return my_redirect('/exam/')
courses = Course.objects.get_queryset().filter(
Q(creator=user) | Q(teachers=user),
is_trial=False).distinct().order_by("-active")
paginator = Paginator(courses, 20)
page = request.GET.get('page')
courses = paginator.get_page(page)
messages.info(request, msg)
context = {'user': user, 'objects': courses}
return my_render_to_response(
request, 'yaksh/moderator_dashboard.html', context
)
def user_login(request):
"""Take the credentials of the user and log the user in."""
user = request.user
context = {}
if user.is_authenticated:
return index(request)
next_url = request.GET.get('next')
if request.method == "POST":
form = UserLoginForm(request.POST)
if form.is_valid():
user = form.cleaned_data
login(request, user)
return index(request, next_url)
else:
context = {"form": form}
else:
form = UserLoginForm()
context = {"form": form}
return my_render_to_response(request, 'yaksh/login.html', context)
@login_required
@email_verified
def special_start(request, micromanager_id=None):
user = request.user
micromanager = get_object_or_404(MicroManager, pk=micromanager_id,
student=user)
course = micromanager.course
quiz = micromanager.quiz
module = course.get_learning_module(quiz)
quest_paper = get_object_or_404(QuestionPaper, quiz=quiz)
if not course.is_enrolled(user):
msg = 'You are not enrolled in {0} course'.format(course.name)
return quizlist_user(request, msg=msg)
if not micromanager.can_student_attempt():
msg = 'Your special attempts are exhausted for {0}'.format(
quiz.description)
return quizlist_user(request, msg=msg)
last_attempt = AnswerPaper.objects.get_user_last_attempt(
quest_paper, user, course.id)
if last_attempt:
if last_attempt.is_attempt_inprogress():
return show_question(
request, last_attempt.current_question(), last_attempt,
course_id=course.id, module_id=module.id,
previous_question=last_attempt.current_question()
)
attempt_num = micromanager.get_attempt_number()
ip = request.META['REMOTE_ADDR']
new_paper = quest_paper.make_answerpaper(user, ip, attempt_num, course.id,
special=True)
micromanager.increment_attempts_utilised()
return show_question(request, new_paper.current_question(), new_paper,
course_id=course.id, module_id=module.id)
@login_required
@email_verified
def start(request, questionpaper_id=None, attempt_num=None, course_id=None,
module_id=None):
"""Check the user cedentials and if any quiz is available,
start the exam."""
user = request.user
# check conditions
try:
quest_paper = QuestionPaper.objects.get(id=questionpaper_id)
except QuestionPaper.DoesNotExist:
msg = 'Quiz not found, please contact your '\
'instructor/administrator.'
if is_moderator(user):
return prof_manage(request, msg=msg)
return view_module(request, module_id=module_id, course_id=course_id,
msg=msg)
if not quest_paper.has_questions():
msg = 'Quiz does not have Questions, please contact your '\
'instructor/administrator.'
if is_moderator(user):
return prof_manage(request, msg=msg)
return view_module(request, module_id=module_id, course_id=course_id,
msg=msg)
course = Course.objects.get(id=course_id)
learning_module = course.learning_module.get(id=module_id)
learning_unit = learning_module.learning_unit.get(quiz=quest_paper.quiz.id)
# unit module active status
if not learning_module.active:
return view_module(request, module_id, course_id)
# unit module prerequiste check
if learning_module.has_prerequisite():
if not learning_module.is_prerequisite_complete(user, course):
msg = "You have not completed the module previous to {0}".format(
learning_module.name)
return course_modules(request, course_id, msg)
if learning_module.check_prerequisite_passes:
if not learning_module.is_prerequisite_passed(user, course):
msg = (
"You have not successfully passed the module"
" previous to {0}".format(learning_module.name)
)
return course_modules(request, course_id, msg)
# is user enrolled in the course
if not course.is_enrolled(user):
msg = 'You are not enrolled in {0} course'.format(course.name)
if is_moderator(user) and course.is_trial:
return prof_manage(request, msg=msg)
return quizlist_user(request, msg=msg)
# if course is active and is not expired
if not course.active or not course.is_active_enrollment():
msg = "{0} is either expired or not active".format(course.name)
if is_moderator(user) and course.is_trial:
return prof_manage(request, msg=msg)
return quizlist_user(request, msg=msg)
# is quiz is active and is not expired
if quest_paper.quiz.is_expired() or not quest_paper.quiz.active:
msg = "{0} is either expired or not active".format(
quest_paper.quiz.description)
if is_moderator(user) and course.is_trial:
return prof_manage(request, msg=msg)
return view_module(request, module_id=module_id, course_id=course_id,
msg=msg)
# prerequisite check and passing criteria for quiz
if learning_unit.has_prerequisite():
if not learning_unit.is_prerequisite_complete(
user, learning_module, course):
msg = "You have not completed the previous Lesson/Quiz/Exercise"
if is_moderator(user) and course.is_trial:
return prof_manage(request, msg=msg)
return view_module(request, module_id=module_id,
course_id=course_id, msg=msg)
# update course status with current unit
_update_unit_status(course_id, user, learning_unit)
# if any previous attempt
last_attempt = AnswerPaper.objects.get_user_last_attempt(
quest_paper, user, course_id)
if last_attempt:
if last_attempt.is_attempt_inprogress():
return show_question(
request, last_attempt.current_question(), last_attempt,
course_id=course_id, module_id=module_id,
previous_question=last_attempt.current_question()
)
attempt_number = last_attempt.attempt_number + 1
else:
attempt_number = 1
# allowed to start
if not quest_paper.can_attempt_now(user, course_id)[0]:
msg = quest_paper.can_attempt_now(user, course_id)[1]
if is_moderator(user):
return prof_manage(request, msg=msg)
return complete(
request, msg, last_attempt.attempt_number, quest_paper.id,
course_id=course_id, module_id=module_id
)
if attempt_num is None and not quest_paper.quiz.is_exercise:
context = {
'user': user,
'questionpaper': quest_paper,
'attempt_num': attempt_number,
'course': course,
'module': learning_module,
}
if is_moderator(user):
context["status"] = "moderator"
return my_render_to_response(request, 'yaksh/intro.html', context)
else:
ip = request.META['REMOTE_ADDR']
if not hasattr(user, 'profile'):
msg = 'You do not have a profile and cannot take the quiz!'
raise Http404(msg)
new_paper = quest_paper.make_answerpaper(user, ip, attempt_number,
course_id)
if new_paper.status == 'inprogress':
return show_question(
request, new_paper.current_question(),
new_paper, course_id=course_id,
module_id=module_id, previous_question=None
)
else:
msg = 'You have already finished the quiz!'
raise Http404(msg)
@login_required
@email_verified
def show_question(request, question, paper, error_message=None,
notification=None, course_id=None, module_id=None,
previous_question=None):
"""Show a question if possible."""
quiz = paper.question_paper.quiz
quiz_type = 'Exam'
can_skip = False
assignment_files = []
qrcode = []
if previous_question:
delay_time = paper.time_left_on_question(previous_question)
else:
delay_time = paper.time_left_on_question(question)
if previous_question and quiz.is_exercise:
is_prev_que_answered = paper.questions_answered.filter(
id=previous_question.id).exists()
if (delay_time <= 0 or is_prev_que_answered):
can_skip = True
question = previous_question
if not question:
msg = 'Congratulations! You have successfully completed the quiz.'
return complete(
request, msg, paper.attempt_number, paper.question_paper.id,
course_id=course_id, module_id=module_id
)
if not quiz.active and not paper.is_special:
reason = 'The quiz has been deactivated!'
return complete(
request, reason, paper.attempt_number, paper.question_paper.id,
course_id=course_id, module_id=module_id
)
if not quiz.is_exercise:
if paper.time_left() <= 0:
reason = 'Your time is up!'
return complete(
request, reason, paper.attempt_number, paper.question_paper.id,
course_id, module_id=module_id
)
else:
quiz_type = 'Exercise'
if paper.questions_answered.filter(id=question.id).exists():
notification = (
'You have already attempted this question successfully'
if question.type == "code" else
'You have already attempted this question'
)
if question.type in ['mcc', 'mcq', 'arrange']:
test_cases = question.get_ordered_test_cases(paper)
else:
test_cases = question.get_test_cases()
if question.type == 'upload':
assignment_files = AssignmentUpload.objects.filter(
assignmentQuestion_id=question.id,
answer_paper=paper
)
handlers = QRcodeHandler.objects.filter(user=request.user,
question=question,
answerpaper=paper)
qrcode = None
if handlers.exists():
handler = handlers.last()
qrcode = handler.qrcode_set.filter(active=True, used=False).last()
files = FileUpload.objects.filter(question_id=question.id, hide=False)
course = Course.objects.get(id=course_id)
module = course.learning_module.get(id=module_id)
all_modules = course.get_learning_modules()
context = {
'question': question,
'paper': paper,
'quiz': quiz,
'error_message': error_message,
'test_cases': test_cases,
'files': files,
'notification': notification,
'last_attempt': question.snippet.encode('unicode-escape'),
'course': course,
'module': module,
'can_skip': can_skip,
'delay_time': delay_time,
'quiz_type': quiz_type,
'all_modules': all_modules,
'assignment_files': assignment_files,
'qrcode': qrcode,
}
answers = paper.get_previous_answers(question)
if answers:
last_attempt = answers[0].answer
if last_attempt:
context['last_attempt'] = last_attempt.encode('unicode-escape')
return my_render_to_response(request, 'yaksh/question.html', context)
@login_required
@email_verified
def skip(request, q_id, next_q=None, attempt_num=None, questionpaper_id=None,
course_id=None, module_id=None):
paper = get_object_or_404(
AnswerPaper, user=request.user, attempt_number=attempt_num,
question_paper=questionpaper_id, course_id=course_id
)
question = get_object_or_404(Question, pk=q_id)
if paper.question_paper.quiz.is_exercise:
paper.start_time = timezone.now()
paper.save()
if request.method == 'POST' and question.type == 'code':
if not paper.answers.filter(question=question, correct=True).exists():
user_code = request.POST.get('answer')
new_answer = Answer(
question=question, answer=user_code,
correct=False, skipped=True,
error=json.dumps([])
)
new_answer.save()
paper.answers.add(new_answer)
if next_q is not None:
next_q = get_object_or_404(Question, pk=next_q)
else:
next_q = paper.next_question(q_id)
return show_question(request, next_q, paper, course_id=course_id,
module_id=module_id)
@login_required
@email_verified
def check(request, q_id, attempt_num=None, questionpaper_id=None,
course_id=None, module_id=None):
"""Checks the answers of the user for particular question"""
user = request.user
paper = get_object_or_404(
AnswerPaper,
user=request.user,
attempt_number=attempt_num,
question_paper=questionpaper_id,
course_id=course_id
)
current_question = get_object_or_404(Question, pk=q_id)
def is_valid_answer(answer):
status = True
if ((current_question.type == "mcc" or
current_question.type == "arrange") and not answer):
status = False
elif answer is None or not str(answer):
status = False
return status
if request.method == 'POST':
# Add the answer submitted, regardless of it being correct or not.
if (paper.time_left() <= -10 or paper.status == "completed"):
reason = 'Your time is up!'
return complete(
request, reason, paper.attempt_number, paper.question_paper.id,
course_id, module_id=module_id
)
if current_question.type == 'mcq':
user_answer = request.POST.get('answer')
elif current_question.type == 'integer':
try:
user_answer = int(request.POST.get('answer'))
except ValueError:
msg = "Please enter an Integer Value"
return show_question(
request, current_question, paper, notification=msg,
course_id=course_id, module_id=module_id,
previous_question=current_question
)
elif current_question.type == 'float':
try:
user_answer = float(request.POST.get('answer'))
except ValueError:
msg = "Please enter a Float Value"
return show_question(request, current_question,
paper, notification=msg,
course_id=course_id, module_id=module_id,
previous_question=current_question)
elif current_question.type == 'string':
user_answer = str(request.POST.get('answer'))
elif current_question.type == 'mcc':
user_answer = request.POST.getlist('answer')
elif current_question.type == 'arrange':
user_answer_ids = request.POST.get('answer').split(',')
user_answer = [int(ids) for ids in user_answer_ids]
elif current_question.type == 'upload':
# if time-up at upload question then the form is submitted without
# validation
assign_files = []
assignments = request.FILES
for i in range(len(assignments)):
assign_files.append(assignments[f"assignment[{i}]"])
if not assign_files:
msg = "Please upload assignment file"
return show_question(
request, current_question, paper, notification=msg,
course_id=course_id, module_id=module_id,
previous_question=current_question
)
uploaded_files = []
AssignmentUpload.objects.filter(
assignmentQuestion_id=current_question.id,
answer_paper_id=paper.id
).delete()
for fname in assign_files:
fname._name = fname._name.replace(" ", "_")
uploaded_files.append(AssignmentUpload(
assignmentQuestion_id=current_question.id,
assignmentFile=fname,
answer_paper_id=paper.id
))
AssignmentUpload.objects.bulk_create(uploaded_files)
user_answer = 'ASSIGNMENT UPLOADED'
new_answer = Answer(
question=current_question, answer=user_answer,
correct=False, error=json.dumps([])
)
new_answer.save()
paper.answers.add(new_answer)
next_q = paper.add_completed_question(current_question.id)
return show_question(request, next_q, paper,
course_id=course_id, module_id=module_id,
previous_question=current_question)
else:
user_answer = request.POST.get('answer')
if not is_valid_answer(user_answer):
msg = "Please submit a valid answer."
return show_question(
request, current_question, paper, notification=msg,
course_id=course_id, module_id=module_id,
previous_question=current_question
)
if current_question in paper.get_questions_answered()\
and current_question.type not in ['code', 'upload']:
new_answer = paper.get_latest_answer(current_question.id)
new_answer.answer = user_answer
new_answer.correct = False
else:
new_answer = Answer(
question=current_question, answer=user_answer,
correct=False, error=json.dumps([])
)
new_answer.save()
uid = new_answer.id
paper.answers.add(new_answer)
# If we were not skipped, we were asked to check. For any non-mcq
# questions, we obtain the results via XML-RPC with the code executed
# safely in a separate process (the code_server.py) running as nobody.
json_data = current_question.consolidate_answer_data(
user_answer, user) if current_question.type == 'code' else None
result = paper.validate_answer(
user_answer, current_question, json_data, uid
)
if current_question.type == 'code':
if (paper.time_left() <= 0 and not
paper.question_paper.quiz.is_exercise):
url = '{0}:{1}'.format(SERVER_HOST_NAME, SERVER_POOL_PORT)
result_details = get_result_from_code_server(url, uid,
block=True)
result = json.loads(result_details.get('result'))
next_question, error_message, paper = _update_paper(
request, uid, result)
return show_question(request, next_question, paper,
error_message, course_id=course_id,
module_id=module_id,
previous_question=current_question)
else:
return JsonResponse(result)
else:
next_question, error_message, paper = _update_paper(
request, uid, result)
return show_question(request, next_question, paper, error_message,
course_id=course_id, module_id=module_id,
previous_question=current_question)
else:
return show_question(request, current_question, paper,
course_id=course_id, module_id=module_id,
previous_question=current_question)
@csrf_exempt
def get_result(request, uid, course_id, module_id):
result = {}
url = '{0}:{1}'.format(SERVER_HOST_NAME, SERVER_POOL_PORT)
result_state = get_result_from_code_server(url, uid)
result['status'] = result_state.get('status')
if result['status'] == 'done':
result = json.loads(result_state.get('result'))
template_path = os.path.join(*[os.path.dirname(__file__),
'templates', 'yaksh',
'error_template.html'
]
)
next_question, error_message, paper = _update_paper(request, uid,
result
)
answer = Answer.objects.get(id=uid)
current_question = answer.question
if result.get('success'):
return show_question(request, next_question, paper, error_message,
course_id=course_id, module_id=module_id,
previous_question=current_question)
else:
with open(template_path) as f:
template_data = f.read()
template = Template(template_data)
context = Context({"error_message": result.get('error')})
render_error = template.render(context)
result["error"] = render_error
return JsonResponse(result)
def _update_paper(request, uid, result):
new_answer = Answer.objects.get(id=uid)
current_question = new_answer.question
paper = new_answer.answerpaper_set.first()
if result.get('success'):
new_answer.marks = (current_question.points * result['weight'] /
current_question.get_maximum_test_case_weight()) \
if current_question.partial_grading and \
current_question.type == 'code' or \
current_question.type == 'upload' else current_question.points
new_answer.correct = result.get('success')
error_message = None
new_answer.error = json.dumps(result.get('error'))
next_question = paper.add_completed_question(current_question.id)