Newer
Older
# -*- coding: utf-8 -*-
from __future__ import division
__copyright__ = "Copyright (C) 2014 Andreas Kloeckner"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import django.forms as forms
from django.utils.safestring import mark_safe
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
from course.page.base import (
AnswerFeedback, PageBaseWithTitle, PageBaseWithValue, markup_to_html)
from course.content import remove_prefix
from course.validation import validate_markup, ValidationError
import six
class ChoiceAnswerForm(StyledForm):
def __init__(self, field, *args, **kwargs):
super(ChoiceAnswerForm, self).__init__(*args, **kwargs)
self.fields["choice"] = field
class ChoiceQuestion(PageBaseWithTitle, PageBaseWithValue):
"""
A page asking the participant to choose one of multiple answers.
.. attribute:: id
|id-page-attr|
.. attribute:: type
``ChoiceQuestion``
.. attribute:: access_rules
|access-rules-page-attr|
.. attribute:: title
|title-page-attr|
.. attribute:: value
|value-page-attr|
.. attribute:: prompt
The page's prompt, written in :ref:`markup`.
.. attribute:: choices
A list of choices, each in :ref:`markup`. Correct
choices are indicated by the prefix ``~CORRECT~``.
.. attribute:: shuffle
Optional. ``True`` or ``False``. If true, the choices will
be presented in random order.
"""
CORRECT_TAG = "~CORRECT~"
@classmethod
def process_choice_string(cls, page_context, s):
s = remove_prefix(cls.CORRECT_TAG, s)
s = markup_to_html(page_context, s)
# allow HTML in option
s = mark_safe(s)
return s
def __init__(self, vctx, location, page_desc):
super(ChoiceQuestion, self).__init__(vctx, location, page_desc)
correct_choice_count = 0
for choice_idx, choice in enumerate(page_desc.choices):
if not isinstance(choice, six.string_types):
raise ValidationError("%s, choice %d: not a string"
% (location, choice_idx+1))
if choice.startswith(self.CORRECT_TAG):
correct_choice_count += 1
if vctx is not None:
validate_markup(vctx, location,
remove_prefix(self.CORRECT_TAG, choice))
if correct_choice_count < 1:
raise ValidationError("%s: one or more correct answer(s) "
"expected, %d found" % (location, correct_choice_count))
def required_attrs(self):
return super(ChoiceQuestion, self).required_attrs() + (
("prompt", "markup"),
("choices", list),
)
def allowed_attrs(self):
return super(ChoiceQuestion, self).allowed_attrs() + (
("shuffle", bool),
)
def markup_body_for_title(self):
return self.page_desc.prompt
def body(self, page_context, page_data):
return markup_to_html(page_context, self.page_desc.prompt)
def make_page_data(self):
import random
perm = range(len(self.page_desc.choices))
if getattr(self.page_desc, "shuffle", False):
random.shuffle(perm)
return {"permutation": perm}
def make_choice_form(self, page_context, page_data, *args, **kwargs):
permutation = page_data["permutation"]
choices = tuple(
(i, self.process_choice_string(
page_context, self.page_desc.choices[src_i]))
for i, src_i in enumerate(permutation))
return ChoiceAnswerForm(
forms.TypedChoiceField(
choices=tuple(choices),
coerce=int,
widget=forms.RadioSelect()),
*args, **kwargs)
def make_form(self, page_context, page_data,
answer_data, answer_is_final):
if answer_data is not None:
form_data = {"choice": answer_data["choice"]}
form = self.make_choice_form(page_context, page_data, form_data)
else:
form = self.make_choice_form(page_context, page_data)
if answer_is_final:
form.fields['choice'].widget.attrs['disabled'] = True
return form
def post_form(self, page_context, page_data, post_data, files_data):
return self.make_choice_form(
page_context, page_data, post_data, files_data)
def answer_data(self, page_context, page_data, form, files_data):
return {"choice": form.cleaned_data["choice"]}
def unpermuted_correct_indices(self):
result = []
for i, choice_text in enumerate(self.page_desc.choices):
if choice_text.startswith(self.CORRECT_TAG):
result.append(i)
return result
def grade(self, page_context, page_data, answer_data, grade_data):
if answer_data is None:
return AnswerFeedback(correctness=0,
feedback="No answer provided.",
normalized_answer=None)
permutation = page_data["permutation"]
choice = answer_data["choice"]
if permutation[choice] in self.unpermuted_correct_indices():
correctness = 1
else:
correctness = 0
return AnswerFeedback(correctness=correctness,
normalized_answer=self.process_choice_string(
page_context,
self.page_desc.choices[permutation[choice]]))
def correct_answer(self, page_context, page_data, answer_data, grade_data):
corr_idx = self.unpermuted_correct_indices()[0]
return ("A correct answer is:%s"
% self.process_choice_string(
page_context,
self.page_desc.choices[corr_idx]).lstrip())