1 # -*- coding: utf-8 -*-
3 from copy import deepcopy
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
11 from .forms import WTEMForm
12 from .models import Submission, DEBUG_KEY, exercises
14 WTEM_CONTEST_STAGE = getattr(settings, 'WTEM_CONTEST_STAGE', 'before')
18 def form(request, key):
19 return globals()['form_' + WTEM_CONTEST_STAGE](request, key)
22 def form_before(request, key):
24 Submission.objects.get(key=key)
25 except Submission.DoesNotExist:
26 return render(request, 'wtem/key_not_found_before.html')
28 return render(request, 'wtem/main_before.html')
31 def form_after(request, key):
32 return render(request, 'wtem/main_after.html')
37 def form_during(request, key):
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')
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)
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)
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)
68 return render(request, 'wtem/thanks.html', dict(end_time=submission.end_time))