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, get_object_or_404
8 from django.views.decorators.cache import never_cache
9 from django.views.decorators.csrf import csrf_exempt
11 from wtem.models import Confirmation
12 from .forms import WTEMForm
13 from .models import Submission, DEBUG_KEY, exercises
15 WTEM_CONTEST_STAGE = getattr(settings, 'WTEM_CONTEST_STAGE', 'before')
19 def form(request, key):
20 return globals()['form_' + WTEM_CONTEST_STAGE](request, key)
23 def form_before(request, key):
25 Submission.objects.get(key=key)
26 except Submission.DoesNotExist:
27 return render(request, 'wtem/key_not_found_before.html')
29 return render(request, 'wtem/main_before.html')
32 def form_after(request, key):
33 return render(request, 'wtem/main_after.html')
38 def form_during(request, key):
40 if WTEM_CONTEST_STAGE != 'during':
41 if request.META['REMOTE_ADDR'] not in getattr(settings, 'WTEM_CONTEST_IP_ALLOW', []):
42 return HttpResponseForbidden('Not allowed')
45 submission = Submission.objects.get(key=key)
46 except Submission.DoesNotExist:
47 if settings.DEBUG and key == DEBUG_KEY:
48 submission = Submission.create(
49 first_name='Debug', last_name='Debug', email='debug@debug.com', key=DEBUG_KEY)
51 return render(request, 'wtem/key_not_found.html')
52 exercises_with_answers = deepcopy(exercises)
53 if submission.answers:
54 answers = json.loads(submission.answers)
57 for exercise in exercises_with_answers:
58 exercise['saved_answer'] = answers.get(str(exercise['id']), '')
59 if exercise['type'] == 'open' and exercise.get('fields'):
60 field_answers = {field['id']: field['text'] for field in exercise['saved_answer']}
61 for field in exercise['fields']:
62 field['saved_answer'] = field_answers.get(field['id'], '')
63 if request.method == 'GET':
64 return render(request, 'wtem/main.html', {'exercises': exercises_with_answers, 'end_time': submission.end_time})
65 elif request.method == 'POST':
66 form = WTEMForm(request.POST, request.FILES, instance=submission)
69 return render(request, 'wtem/thanks.html', dict(end_time=submission.end_time))
74 def confirmation(request, id, key):
75 conf = get_object_or_404(Confirmation, id=id, key=key)
76 was_confirmed = conf.confirmed
80 return render(request, 'wtem/confirmed.html', {'confirmation': conf, 'was_confirmed': was_confirmed})