generated from ocadotechnology/codeforlife-template-backend
-
Notifications
You must be signed in to change notification settings - Fork 24
/
teach.py
1190 lines (1000 loc) · 39.4 KB
/
teach.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 csv
import json
from datetime import datetime, timedelta
from enum import Enum
from functools import partial, wraps
from uuid import uuid4
import pytz
from aimmo.models import Game
from common.helpers.emails import send_verification_email
from common.helpers.generators import (
generate_access_code,
generate_login_id,
generate_password,
get_hashed_login_id,
)
from common.models import (
Class,
DailyActivity,
JoinReleaseStudent,
Student,
Teacher,
)
from common.permissions import check_teacher_authorised, logged_in_as_teacher
from django.contrib import messages as messages
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth.models import User
from django.contrib.staticfiles.storage import staticfiles_storage
from django.forms.formsets import formset_factory
from django.http import (
Http404,
HttpResponse,
HttpResponseRedirect,
JsonResponse,
)
from django.shortcuts import get_object_or_404, render
from django.urls import reverse, reverse_lazy
from django.utils import timezone
from django.views.decorators.http import require_POST
from game.views.level_selection import get_blockly_episodes, get_python_episodes
from portal.forms.teach import (
BaseTeacherDismissStudentsFormSet,
BaseTeacherMoveStudentsDisambiguationFormSet,
ClassCreationForm,
ClassEditForm,
ClassLevelControlForm,
ClassMoveForm,
StudentCreationForm,
TeacherDismissStudentsForm,
TeacherEditStudentForm,
TeacherMoveStudentDisambiguationForm,
TeacherMoveStudentsDestinationForm,
TeacherSetStudentPass,
)
from portal.helpers.ratelimit import clear_ratelimit_cache_for_user
from portal.views.registration import handle_reset_password_tracking
from reportlab.lib.colors import black, red
from reportlab.lib.pagesizes import A4
from reportlab.lib.utils import ImageReader
from reportlab.pdfgen import canvas
from rest_framework import status
from codeforlife import settings
STUDENT_PASSWORD_LENGTH = 6
REMINDER_CARDS_PDF_ROWS = 8
REMINDER_CARDS_PDF_COLUMNS = 1
REMINDER_CARDS_PDF_WARNING_TEXT = (
"Please ensure students keep login details in a secure place"
)
@login_required(login_url=reverse_lazy("teacher_login"))
@user_passes_test(logged_in_as_teacher, login_url=reverse_lazy("teacher_login"))
def teacher_onboarding_create_class(request):
"""
Onboarding view for creating a class (and organisation if there isn't one, yet)
"""
teacher = request.user.new_teacher
requests = Student.objects.filter(
pending_class_request__teacher=teacher, new_user__is_active=True
)
if not teacher.school:
return HttpResponseRedirect(reverse_lazy("onboarding-organisation"))
if request.method == "POST":
form = ClassCreationForm(request.POST, teacher=teacher)
if form.is_valid():
created_class = create_class(form, teacher)
messages.success(
request,
"The class '{className}' has been created successfully.".format(
className=created_class.name
),
)
return HttpResponseRedirect(
reverse_lazy(
"onboarding-class",
kwargs={"access_code": created_class.access_code},
)
)
else:
form = ClassCreationForm(teacher=teacher)
classes = Class.objects.filter(teacher=teacher)
return render(
request,
"portal/teach/onboarding_classes.html",
{"form": form, "classes": classes, "requests": requests},
)
def create_class(form, class_teacher, class_creator=None):
classmate_progress = bool(form.cleaned_data["classmate_progress"])
klass = Class.objects.create(
name=form.cleaned_data["class_name"],
teacher=class_teacher,
access_code=generate_access_code(),
classmates_data_viewable=classmate_progress,
created_by=class_teacher if class_creator is None else class_creator,
)
return klass
def generate_student_url(request, student, login_id):
return request.build_absolute_uri(
reverse(
"student_direct_login",
kwargs={"user_id": student.new_user.id, "login_id": login_id},
)
)
def process_edit_class(request, access_code, onboarding_done, next_url):
"""
Handles student creation both during onboarding or on the class page
"""
klass = get_object_or_404(Class, access_code=access_code)
teacher = request.user.new_teacher
students = Student.objects.filter(
class_field=klass, new_user__is_active=True
).order_by("new_user__first_name")
check_teacher_authorised(request, klass.teacher)
if request.method == "POST":
new_students_form = StudentCreationForm(klass, request.POST)
if new_students_form.is_valid():
students_info = []
for name in new_students_form.strippedNames:
password = generate_password(STUDENT_PASSWORD_LENGTH)
# generate uuid for url and store the hashed
login_id, hashed_login_id = generate_login_id()
new_student = Student.objects.schoolFactory(
klass=klass,
name=name,
password=password,
login_id=hashed_login_id,
)
login_url = generate_student_url(request, new_student, login_id)
students_info.append(
{
"id": new_student.new_user.id,
"name": name,
"password": password,
"login_url": login_url,
}
)
return render(
request,
"portal/teach/onboarding_print.html",
{
"class": klass,
"students_info": students_info,
"onboarding_done": onboarding_done,
"query_data": json.dumps(students_info),
"class_url": request.build_absolute_uri(
reverse(
"student_login",
kwargs={"access_code": klass.access_code},
)
),
},
)
else:
new_students_form = StudentCreationForm(klass)
classes = Class.objects.filter(teacher=teacher)
return render(
request,
next_url,
{
"class": klass,
"classes": classes,
"students": students,
"new_students_form": new_students_form,
"num_students": len(students),
},
)
@login_required(login_url=reverse_lazy("teacher_login"))
@user_passes_test(logged_in_as_teacher, login_url=reverse_lazy("teacher_login"))
def teacher_onboarding_edit_class(request, access_code):
"""
Adding students to a class during the onboarding process
"""
return process_edit_class(
request,
access_code,
onboarding_done=False,
next_url="portal/teach/onboarding_students.html",
)
@login_required(login_url=reverse_lazy("teacher_login"))
@user_passes_test(logged_in_as_teacher, login_url=reverse_lazy("teacher_login"))
def teacher_view_class(request, access_code):
"""
Adding students to a class after the onboarding process has been completed
"""
return process_edit_class(
request,
access_code,
onboarding_done=True,
next_url="portal/teach/class.html",
)
@require_POST
@login_required(login_url=reverse_lazy("teacher_login"))
@user_passes_test(logged_in_as_teacher, login_url=reverse_lazy("teacher_login"))
def teacher_delete_class(request, access_code):
klass = get_object_or_404(Class, access_code=access_code)
games = Game.objects.filter(game_class=klass)
# check user authorised to see class
try:
check_teacher_authorised(request, klass.teacher)
except Http404:
return JsonResponse(
{"error": "User not authorised."},
status=status.HTTP_400_BAD_REQUEST,
)
if Student.objects.filter(
class_field=klass, new_user__is_active=True
).exists():
return JsonResponse(
{
"error": "This class still has students, please remove or delete them all before deleting the class."
},
status=status.HTTP_400_BAD_REQUEST,
)
for game in games:
game.is_archived = True
game.save()
klass.anonymise()
return HttpResponse(status=status.HTTP_204_NO_CONTENT)
@login_required(login_url=reverse_lazy("teacher_login"))
@user_passes_test(logged_in_as_teacher, login_url=reverse_lazy("teacher_login"))
def teacher_delete_students(request, access_code):
klass = get_object_or_404(Class, access_code=access_code)
# check user is authorised to deal with class
check_teacher_authorised(request, klass.teacher)
# get student objects for students to be deleted, confirming they are in the class
student_ids = json.loads(request.POST.get("transfer_students", "[]"))
students = [
get_object_or_404(Student, id=i, class_field=klass) for i in student_ids
]
def __anonymise(user):
# Delete all personal data from inactive user and mark as inactive.
# Student only has random username, password, first_name
user.first_name = "Deleted"
user.last_name = "User"
user.is_active = False
user.save()
# Delete all of the students
for student in students:
# If the student has previously logged in, anonymise
user = student.new_user
if user.last_login:
__anonymise(user)
# remove login id so they can't log in with direct link anymore
student.login_id = ""
student.save()
else: # otherwise, just delete
student.new_user.delete()
return HttpResponseRedirect(
reverse_lazy("view_class", kwargs={"access_code": access_code})
)
@login_required(login_url=reverse_lazy("teacher_login"))
@user_passes_test(logged_in_as_teacher, login_url=reverse_lazy("teacher_login"))
def teacher_edit_class(request, access_code):
"""
Editing additional class details. Provides functionality for:
- Editing the class name, sharing and joining settings
- Locking or unlocking specific Rapid Router levels
- Transferring the class to another teacher
"""
access_code = access_code.upper()
klass = get_object_or_404(Class, access_code=access_code)
old_teacher = klass.teacher
other_teachers = Teacher.objects.filter(school=old_teacher.school).exclude(
user=old_teacher.user
)
# check user authorised to see class
check_teacher_authorised(request, klass.teacher)
external_requests_message = klass.get_requests_message()
blockly_episodes = get_blockly_episodes(request)
python_episodes = get_python_episodes(request)
locked_levels = klass.locked_levels.all()
locked_levels_ids = [locked_level.id for locked_level in locked_levels]
# form = ClassEditForm(
# initial={
# "name": klass.name,
# "classmate_progress": klass.classmates_data_viewable,
# }
# )
# level_control_form = ClassLevelControlForm()
# class_move_form = ClassMoveForm(other_teachers)
if request.method == "POST":
if "class_edit_submit" in request.POST:
form = ClassEditForm(request.POST)
if form.is_valid():
return process_edit_class_form(request, klass, form)
elif "level_control_submit" in request.POST:
level_control_form = ClassLevelControlForm(request.POST)
if level_control_form.is_valid():
return process_level_control_form(
request, klass, blockly_episodes, python_episodes
)
# return render(
# request,
# "portal/teach/teacher_edit_class.html",
# {
# "form": form,
# "class_move_form": class_move_form,
# "level_control_form": level_control_form,
# "blockly_episodes": blockly_episodes,
# "python_episodes": python_episodes,
# "locked_levels": locked_levels_ids,
# "class": klass,
# "external_requests_message": external_requests_message,
# },
# )
return JsonResponse(
{
"blockly_episodes": blockly_episodes,
"python_episodes": python_episodes,
"locked_levels": locked_levels_ids,
"class": {
"name": klass.name,
"classmate_progress": klass.classmates_data_viewable,
},
"external_requests_message": external_requests_message,
}
)
def process_edit_class_form(request, klass, form):
name = form.cleaned_data["name"]
classmate_progress = bool(form.cleaned_data["classmate_progress"])
external_requests_setting = form.cleaned_data["external_requests"]
if external_requests_setting != "":
# Change submitted for external requests
hours = int(external_requests_setting)
if hours == 0:
# Setting to off
klass.always_accept_requests = False
klass.accept_requests_until = None
messages.info(
request,
"Class set successfully to never receive requests from external students.",
)
elif hours < 1000:
# Setting to number of hours
klass.always_accept_requests = False
klass.accept_requests_until = timezone.now() + timedelta(
hours=hours
)
messages.info(
request,
"Class set successfully to receive requests from external students until "
+ klass.accept_requests_until.strftime("%d-%m-%Y %H:%M")
+ " "
+ timezone.get_current_timezone_name(),
)
else:
# Setting to always on
klass.always_accept_requests = True
klass.accept_requests_until = None
messages.info(
request,
"Class set successfully to always receive requests from external students (not recommended)",
)
klass.name = name
klass.classmates_data_viewable = classmate_progress
klass.save()
# messages.success(
# request, "The class's settings have been changed successfully."
# )
# return HttpResponseRedirect(
# reverse_lazy("view_class", kwargs={"access_code": klass.access_code})
# )
return HttpResponse()
def process_level_control_form(
request, klass, blockly_episodes, python_episodes
):
"""
Find the levels that the user wants to lock and lock them for the specific class.
:param request: The request sent by the user submitting the form.
:param klass: The class for which the levels are being locked / unlocked.
:param blockly_episodes: The set of Blockly Episodes in the game.
:param python_episodes: The set of Python Episodes in the game.
:return: A redirect to the teacher dashboard with a success message.
"""
levels_to_lock_ids = []
mark_levels_to_lock_in_episodes(
request, blockly_episodes, levels_to_lock_ids
)
mark_levels_to_lock_in_episodes(
request, python_episodes, levels_to_lock_ids
)
klass.locked_levels.clear()
[
klass.locked_levels.add(levels_to_lock_id)
for levels_to_lock_id in levels_to_lock_ids
]
messages.success(request, "Your level preferences have been saved.")
activity_today = DailyActivity.objects.get_or_create(
date=datetime.now().date()
)[0]
activity_today.level_control_submits += 1
activity_today.save()
return HttpResponseRedirect(reverse_lazy("dashboard"))
def mark_levels_to_lock_in_episodes(request, episodes, levels_to_lock_ids):
"""
For a given set of Episodes, find which Levels are to be locked. This is done by checking the POST request data.
If a Level ID is missing from the request.POST, it means it needs to be locked, and if the entire Episode is missing
from the request.POST, it means all the Levels under that Episode need to be locked.
:param request: The request sent by the user submitting the form.
:param episodes: The set of Episodes, in this case either the Blockly Episodes or the Python Episodes.
:param levels_to_lock_ids: A list of Level IDs marked to be locked.
"""
for episode in episodes:
episode_name = episode["name"]
episode_levels = episode["levels"]
if episode_name in request.POST:
[
levels_to_lock_ids.append(episode_level["id"])
for episode_level in episode_levels
if str(episode_level["id"])
not in request.POST.getlist(episode_name)
]
else:
[
levels_to_lock_ids.append(episode_level["id"])
for episode_level in episode_levels
]
@login_required(login_url=reverse_lazy("teacher_login"))
@user_passes_test(logged_in_as_teacher, login_url=reverse_lazy("teacher_login"))
def teacher_move_class(request):
access_code = request.POST.get("access_code", "")
new_teacher_id = request.POST.get("teacher_id", "")
try:
klass = get_object_or_404(Class, access_code=access_code)
new_teacher = get_object_or_404(Teacher, id=new_teacher_id)
except Http404:
return HttpResponse(status=status.HTTP_404_NOT_FOUND)
klass.teacher = new_teacher
klass.save()
return HttpResponse()
@login_required(login_url=reverse_lazy("teacher_login"))
@user_passes_test(logged_in_as_teacher, login_url=reverse_lazy("teacher_login"))
def teacher_edit_student(request, pk):
"""
Changing a student's details
"""
student = get_object_or_404(Student, id=pk)
check_teacher_authorised(request, student.class_field.teacher)
name_form = TeacherEditStudentForm(
student, initial={"name": student.new_user.first_name}
)
password_form = TeacherSetStudentPass()
set_password_mode = False
if request.method == "POST":
if "name" in request.POST:
student_name = request.POST.get("name")
if Student.objects.filter(
new_user__first_name=student_name
).exists():
return JsonResponse(
{
"message": f"There is already a student called {student_name} in this class"
},
status=400,
)
name_form = TeacherEditStudentForm(student, request.POST)
if name_form.is_valid():
name = name_form.cleaned_data["name"]
student.new_user.first_name = name
student.new_user.save()
student.save()
return JsonResponse(
{
"message": "The student's details have been changed successfully.",
}
)
elif "confirm_password" in request.POST:
password_form = TeacherSetStudentPass(request.POST)
if password_form.is_valid():
return process_reset_password_form(
request, student, password_form
)
return JsonResponse(
{
"message": "Your details were not updated due to incorrect details"
},
status=400,
)
else:
return HttpResponse(status=405)
def process_reset_password_form(request, student, password_form):
# check not default value for CharField
new_password = password_form.cleaned_data["password"]
if new_password:
# generate uuid for url and store the hashed
uuidstr = uuid4().hex
login_id = get_hashed_login_id(uuidstr)
protocol = settings.SERVICE_PROTOCOL
domain = request.headers.get("host", "")
login_url = (
f"{protocol}://{domain}/api/u/{student.new_user.id}/{uuidstr}/"
)
students_info = [
{
"id": student.new_user.id,
"name": student.new_user.first_name,
"password": new_password,
"login_url": login_url,
}
]
handle_reset_password_tracking(request, "SCHOOL_STUDENT")
student.new_user.set_password(new_password)
student.new_user.save()
student.login_id = login_id
clear_ratelimit_cache_for_user(
f"{student.new_user.first_name},{student.class_field.access_code}"
)
student.blocked_time = datetime.now(tz=pytz.utc) - timedelta(days=1)
student.save()
access_code = student.class_field.access_code
frontend_link = request.headers.get("referer", "")
student_login_link = "".join([frontend_link, "login/student"])
class_login_link = "/".join([student_login_link, access_code])
return JsonResponse(
{
"student_login_link": student_login_link,
"class_link": class_login_link,
"access_code": access_code,
"class": student.class_field.name,
"students_info": students_info,
"onboarding_done": True,
"query_data": students_info, # this field could be redundant
}
)
@login_required(login_url=reverse_lazy("teacher_login"))
@user_passes_test(logged_in_as_teacher, login_url=reverse_lazy("teacher_login"))
def teacher_dismiss_students(request, access_code):
"""
Dismiss a student (make them independent)
"""
klass = get_object_or_404(Class, access_code=access_code)
check_teacher_authorised(request, klass.teacher)
# get student objects for students to be dismissed, confirming they are in the class
student_ids = json.loads(request.POST.get("transfer_students", "[]"))
students = [
get_object_or_404(Student, id=i, class_field=klass) for i in student_ids
]
TeacherDismissStudentsFormSet = formset_factory(
wraps(TeacherDismissStudentsForm)(partial(TeacherDismissStudentsForm)),
extra=0,
formset=BaseTeacherDismissStudentsFormSet,
)
if is_right_dismiss_form(request):
formset = TeacherDismissStudentsFormSet(request.POST)
if formset.is_valid():
return process_dismiss_student_form(
request, formset, klass, access_code
)
else:
initial_data = [
{
"orig_name": student.new_user.first_name,
"name": student.new_user.first_name,
"email": "",
}
for student in students
]
formset = TeacherDismissStudentsFormSet(initial=initial_data)
return render(
request,
"portal/teach/teacher_dismiss_students.html",
{"formset": formset, "class": klass, "students": students},
)
def is_right_dismiss_form(request):
return request.method == "POST" and "submit_dismiss" in request.POST
def process_dismiss_student_form(request, formset, klass, access_code):
failed_users = [] # users that failed to be transferred
for data in formset.cleaned_data:
# check if email is already used
users_with_email = User.objects.filter(email=data["email"])
# email is already taken, skip this user
if users_with_email.exists():
failed_users.append(data["orig_name"])
continue
student = get_object_or_404(
Student,
class_field=klass,
new_user__first_name__iexact=data["orig_name"],
)
student.class_field = None
student.new_user.first_name = data["name"]
student.new_user.username = data["email"]
student.new_user.email = data["email"]
student.save()
student.new_user.save()
student.new_user.userprofile.save()
# log the data
joinrelease = JoinReleaseStudent.objects.create(
student=student, action_type=JoinReleaseStudent.RELEASE
)
joinrelease.save()
send_verification_email(request, student.new_user, data)
if not failed_users:
messages.success(
request,
"The students have been released successfully from the class.",
)
else:
messages.warning(
request,
f"The following students could not be released: {', '.join(failed_users)}. "
"Please make sure the email has not been registered to another account.",
)
return HttpResponseRedirect(
reverse_lazy("view_class", kwargs={"access_code": access_code})
)
@login_required(login_url=reverse_lazy("teacher_login"))
@user_passes_test(logged_in_as_teacher, login_url=reverse_lazy("teacher_login"))
def teacher_class_password_reset(request, access_code):
"""
Reset passwords for one or more students
"""
klass = get_object_or_404(Class, access_code=access_code)
# check user authorised to see class
check_teacher_authorised(request, klass.teacher)
student_ids = json.loads(request.POST.get("transfer_students", "[]"))
students = [
get_object_or_404(Student, id=i, class_field=klass) for i in student_ids
]
students_info = []
handle_reset_password_tracking(request, "SCHOOL_STUDENT", access_code)
for student in students:
password = generate_password(STUDENT_PASSWORD_LENGTH)
# generate uuid for url and store the hashed
login_id, hashed_login_id = generate_login_id()
login_url = generate_student_url(request, student, login_id)
students_info.append(
{
"id": student.new_user.id,
"name": student.new_user.first_name,
"password": password,
"login_url": login_url,
}
)
student.new_user.set_password(password)
student.new_user.save()
student.login_id = hashed_login_id
clear_ratelimit_cache_for_user(
f"{student.new_user.first_name},{access_code}"
)
student.blocked_time = datetime.now(tz=pytz.utc) - timedelta(days=1)
student.save()
return render(
request,
"portal/teach/onboarding_print.html",
{
"class": klass,
"onboarding_done": True,
"passwords_reset": True,
"students_info": students_info,
"query_data": json.dumps(students_info),
"class_url": request.build_absolute_uri(
reverse(
"student_login", kwargs={"access_code": klass.access_code}
)
),
},
)
@login_required(login_url=reverse_lazy("teacher_login"))
@user_passes_test(logged_in_as_teacher, login_url=reverse_lazy("teacher_login"))
def teacher_move_students(request, access_code):
"""
Move students
"""
klass = get_object_or_404(Class, access_code=access_code)
# check user is authorised to deal with class
check_teacher_authorised(request, klass.teacher)
transfer_students = request.POST.get("transfer_students", "[]")
school = klass.teacher.school
# get classes in same school
classes = school.classes()
classes.remove(klass)
form = TeacherMoveStudentsDestinationForm(classes)
return render(
request,
"portal/teach/teacher_move_students.html",
{
"transfer_students": transfer_students,
"old_class": klass,
"form": form,
},
)
@login_required(login_url=reverse_lazy("teacher_login"))
@user_passes_test(logged_in_as_teacher, login_url=reverse_lazy("teacher_login"))
def teacher_move_students_to_class(request, access_code):
"""
Disambiguation for moving students (teacher gets to rename the students to avoid clashes)
"""
old_class = get_object_or_404(Class, access_code=access_code)
new_class_id = request.POST.get("new_class", None)
new_class = get_object_or_404(Class, id=new_class_id)
check_if_move_authorised(request, old_class, new_class)
transfer_students_ids = json.loads(
request.POST.get("transfer_students", "[]")
)
# get student objects for students to be transferred, confirming they are in the old class still
transfer_students = [
get_object_or_404(Student, id=i, class_field=old_class)
for i in transfer_students_ids
]
# get new class' students
new_class_students = Student.objects.filter(
class_field=new_class, new_user__is_active=True
).order_by("new_user__first_name")
TeacherMoveStudentDisambiguationFormSet = formset_factory(
wraps(TeacherMoveStudentDisambiguationForm)(
partial(TeacherMoveStudentDisambiguationForm)
),
extra=0,
formset=BaseTeacherMoveStudentsDisambiguationFormSet,
)
if is_right_move_form(request):
formset = TeacherMoveStudentDisambiguationFormSet(
new_class, request.POST
)
if formset.is_valid():
return process_move_students_form(
request, formset, old_class, new_class
)
else:
# format the students for the form
initial_data = [
{
"orig_name": student.new_user.first_name,
"name": student.new_user.first_name,
}
for student in transfer_students
]
formset = TeacherMoveStudentDisambiguationFormSet(
new_class, initial=initial_data
)
return render(
request,
"portal/teach/teacher_move_students_to_class.html",
{
"formset": formset,
"old_class": old_class,
"new_class": new_class,
"new_class_students": new_class_students,
"transfer_students": transfer_students,
},
)
def check_if_move_authorised(request, old_class, new_class):
# check user is authorised to deal with class
if request.user.new_teacher != old_class.teacher:
raise Http404
# check teacher authorised to transfer to new class
if request.user.new_teacher.school != new_class.teacher.school:
raise Http404
def is_right_move_form(request):
return request.method == "POST" and "submit_disambiguation" in request.POST
def process_move_students_form(request, formset, old_class, new_class):
old_teacher = old_class.teacher
new_teacher = new_class.teacher
for name_update in formset.cleaned_data:
student = get_object_or_404(
Student,
class_field=old_class,
new_user__first_name__iexact=name_update["orig_name"],
)
student.class_field = new_class
student.new_user.first_name = name_update["name"]
student.save()
student.new_user.save()
messages.success(
request, "The students have been transferred successfully."
)
return HttpResponseRedirect(
reverse_lazy(
"view_class", kwargs={"access_code": old_class.access_code}
)
)
class DownloadType(Enum):
CSV = 1
LOGIN_CARDS = 2
PRIMARY_PACK = 3
PYTHON_PACK = 4
# This method was added due to weird behavior of
# dictionaries keys and list indexes when passing
# data from frontend to backend. If you know a method
# to fix the dictionary issue, feel free to use it and
# delete this method
def expand_key(dictionary):
expanded = {}
for key, value in dictionary.items():
keys = key.split("[")
keys = [k.replace("]", "") for k in keys]
temp = expanded
for i, k in enumerate(keys[:-1]):
if k.isdigit():
k = int(k)
if not isinstance(temp, list):
temp = []
while len(temp) <= k:
temp.append({})
if keys[i - 1] in expanded:
expanded[keys[i - 1]] = temp
else:
temp[keys[i - 1]] = temp
temp = temp[k]
else:
if k not in temp:
temp[k] = {}
temp = temp[k]
temp[keys[-1]] = value[0] if len(value) == 1 else value
return expanded
# TODO: this function had a method that adds the download PDF analytic, we should
# add it back in somewhere else at some point
# @login_required(login_url=reverse_lazy("teacher_login"))
# @user_passes_test(logged_in_as_teacher, login_url=reverse_lazy("teacher_login"))
# def teacher_print_reminder_cards(request, access_code):
# response = HttpResponse(content_type="application/pdf")
# response["Content-Disposition"] = 'filename="student_reminder_cards.pdf"'
# p = canvas.Canvas(response, pagesize=A4)
# # Define constants that determine the look of the cards
# PAGE_WIDTH, PAGE_HEIGHT = A4
# PAGE_MARGIN = PAGE_WIDTH // 16
# INTER_CARD_MARGIN = PAGE_WIDTH // 64
# CARD_PADDING = PAGE_WIDTH // 48
# # rows and columns on page
# NUM_X = REMINDER_CARDS_PDF_COLUMNS
# NUM_Y = REMINDER_CARDS_PDF_ROWS
# CARD_WIDTH = (PAGE_WIDTH - PAGE_MARGIN * 2) // NUM_X
# CARD_HEIGHT = (PAGE_HEIGHT - PAGE_MARGIN * 4) // NUM_Y
# CARD_INNER_HEIGHT = CARD_HEIGHT - CARD_PADDING * 2
# # logo_image = ImageReader(
# # staticfiles_storage.path("portal/img/logo_cfl_reminder_cards.jpg")
# # )
# klass = get_object_or_404(Class, access_code=access_code)
# # Check auth
# check_teacher_authorised(request, klass.teacher)