ccfca125fd563f985af1fd320326d830904b848c
[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     answers = json.loads(submission.answers)
53     for exercise in exercises_with_answers:
54         exercise['saved_answer'] = answers[str(exercise['id'])]
55         if exercise['type'] == 'open' and exercise.get('fields'):
56             field_answers = {field['id']: field['text'] for field in exercise['saved_answer']}
57             for field in exercise['fields']:
58                 field['saved_answer'] = field_answers[field['id']]
59     if request.method == 'GET':
60         return render(request, 'wtem/main.html', {'exercises': exercises_with_answers, 'end_time': submission.end_time})
61     elif request.method == 'POST':
62         form = WTEMForm(request.POST, request.FILES, instance=submission)
63         if form.is_valid():
64             form.save()
65             return render(request, 'wtem/thanks.html', dict(end_time=submission.end_time))
66         else:
67             raise Exception