Django 1.6
[koed-quiz.git] / apps / quiz / views.py
1 # -*- coding: utf-8 -*-
2 # This file is part of KOED-Quiz, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 from django.shortcuts import get_object_or_404, render, redirect
6
7 from quiz.forms import QuestionForm
8 from quiz.models import Quiz
9
10
11 def question(request, slug=None):
12     if slug is None:
13         question = Quiz.current().start()
14         request.session['ticket'] = [request.path]
15     else:
16         question = get_object_or_404(Quiz.current().question_set, slug=slug)
17
18     ticket = request.session.get('ticket', [])
19     valid = request.path in ticket
20
21     if valid:
22         cur_index = ticket.index(request.path)
23         if cur_index:
24             previous_url = ticket[cur_index - 1]
25     elif ticket:
26         valid_url = ticket[-1]
27
28     if request.method == 'POST' and valid:
29         form = QuestionForm(question, request.POST)
30         if form.is_valid():
31
32             answer = form.cleaned_data['answer']
33             where_to = answer.where_to()
34
35             del ticket[cur_index + 1:]
36             try:
37                 del ticket[ticket.index(where_to) + 1:]
38             except ValueError:
39                 ticket.append(where_to)
40
41             request.session['ticket'] = ticket
42
43             return redirect(where_to)
44     else:
45         form = QuestionForm(question)
46
47     return render(request, "quiz/question_detail.html", locals())
48
49
50 def result(request, slug=None):
51     ticket = request.session.get('ticket', [])
52     valid = request.path in ticket
53
54     if valid:
55         cur_index = ticket.index(request.path)
56         if cur_index:
57             previous_url = ticket[cur_index - 1]
58     elif ticket:
59         valid_url = ticket[-1]
60
61     result = get_object_or_404(Quiz.current().result_set, slug=slug)
62     return render(request, "quiz/result_detail.html", locals())
63