update cybernaut trainers form
[edumed.git] / wtem / views.py
1 # -*- coding: utf-8 -*-
2 import json
3 from copy import deepcopy
4
5 from django.conf import settings
6 from django.http import HttpResponseForbidden
7 from django.shortcuts import render
8 from django.views.decorators.cache import never_cache
9 from django.views.decorators.csrf import csrf_exempt
10
11 from .forms import WTEMForm
12 from .models import Submission, DEBUG_KEY, exercises
13
14 WTEM_CONTEST_STAGE = getattr(settings, 'WTEM_CONTEST_STAGE', 'before')
15
16
17 @csrf_exempt
18 def form(request, key):
19     return globals()['form_' + WTEM_CONTEST_STAGE](request, key)
20
21
22 def form_before(request, key):
23     try:
24         Submission.objects.get(key=key)
25     except Submission.DoesNotExist:
26         return render(request, 'wtem/key_not_found_before.html')
27     else:
28         return render(request, 'wtem/main_before.html')
29
30
31 def form_after(request, key):
32     return render(request, 'wtem/main_after.html')
33
34
35 @never_cache
36 @csrf_exempt
37 def form_during(request, key):
38
39     if WTEM_CONTEST_STAGE != 'during':
40         if request.META['REMOTE_ADDR'] not in getattr(settings, 'WTEM_CONTEST_IP_ALLOW', []):
41             return HttpResponseForbidden('Not allowed')
42
43     try:
44         submission = Submission.objects.get(key=key)
45     except Submission.DoesNotExist:
46         if settings.DEBUG and key == DEBUG_KEY:
47             submission = Submission.create(
48                 first_name='Debug', last_name='Debug', email='debug@debug.com', key=DEBUG_KEY)
49         else:
50             return render(request, 'wtem/key_not_found.html')
51     exercises_with_answers = deepcopy(exercises)
52     if submission.answers:
53         answers = json.loads(submission.answers)
54     else:
55         answers = {}
56     for exercise in exercises_with_answers:
57         exercise['saved_answer'] = answers.get(str(exercise['id']), '')
58         if exercise['type'] == 'open' and exercise.get('fields'):
59             field_answers = {field['id']: field['text'] for field in exercise['saved_answer']}
60             for field in exercise['fields']:
61                 field['saved_answer'] = field_answers.get(field['id'], '')
62     if request.method == 'GET':
63         return render(request, 'wtem/main.html', {'exercises': exercises_with_answers, 'end_time': submission.end_time})
64     elif request.method == 'POST':
65         form = WTEMForm(request.POST, request.FILES, instance=submission)
66         if form.is_valid():
67             form.save()
68             return render(request, 'wtem/thanks.html', dict(end_time=submission.end_time))
69         else:
70             raise Exception