Newer
Older
__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.
"""
from django.utils.translation import gettext, gettext_lazy as _
from course.page.base import (
AnswerFeedback,
PageBaseWithCorrectAnswer,
PageBaseWithHumanTextFeedback,
PageBaseWithTitle,
PageBaseWithValue,
get_editor_interaction_mode,
markup_to_html,
)
from course.validation import ValidationError, validate_struct
from relate.utils import Struct, StyledForm, string_concat
CORRECT_ANSWER_PATTERN = string_concat(_("A correct answer is"), ": '%s'.")
class TextAnswerForm(StyledForm):
Andreas Klöckner
committed
# prevents form submission with codemirror's empty textarea
use_required_attribute = False
def get_text_widget(widget_type, check_only=False,
interaction_mode=None, initial_text=None):
"""Returns None if no widget found."""
if widget_type in [None, "text_input"]:
if check_only:
return True
widget = forms.TextInput()
widget.attrs["autofocus"] = None
Andreas Klöckner
committed
return widget, None
elif widget_type == "textarea":
if check_only:
return True
widget = forms.Textarea()
Andreas Klöckner
committed
return widget, None
elif widget_type.startswith("editor:"):
if check_only:
return True
Andreas Klöckner
committed
from course.utils import get_codemirror_widget
cm_widget, cm_help_text = get_codemirror_widget(
language_mode=widget_type[widget_type.find(":")+1:],
Andreas Klöckner
committed
return cm_widget, cm_help_text
Andreas Klöckner
committed
return None, None
Andreas Klöckner
committed
def __init__(self, read_only, interaction_mode, validators, *args, **kwargs):
widget_type = kwargs.pop("widget_type", "text_input")
initial_text = kwargs.pop("initial_text", None)
super().__init__(*args, **kwargs)
Andreas Klöckner
committed
widget, help_text = self.get_text_widget(
Andreas Klöckner
committed
interaction_mode=interaction_mode)
self.validators = validators
self.fields["answer"] = forms.CharField(
required=True,
Andreas Klöckner
committed
widget=widget,
cleaned_data = super().clean()
answer = cleaned_data.get("answer", "")
Andreas Klöckner
committed
for i, validator in enumerate(self.validators):
try:
validator.validate(answer)
except forms.ValidationError:
if i + 1 == len(self.validators):
# last one, and we flunked -> not valid
raise
else:
# Found one that will take the input. Good enough.
break
class RELATEPageValidator:
type = "relate_page"
def __init__(self, vctx, location, validator_desc):
self.validator_desc = validator_desc
validate_struct(
vctx,
location,
validator_desc,
required_attrs=(
("type", str),
),
allowed_attrs=(
("page_type", str),
),
)
def validate(self, new_page_source):
import yaml
page_desc = dict_to_struct(yaml.safe_load(new_page_source))
from course.validation import ValidationContext, validate_flow_page
vctx = ValidationContext(
# FIXME
repo=None,
commit_sha=None)
ifaint
committed
validate_flow_page(vctx, "submitted page", page_desc)
if page_desc.type != self.validator_desc.page_type:
raise ValidationError(gettext("page must be of type '%s'")
raise forms.ValidationError("%(err_type)s: %(err_str)s"
% {"err_type": tp.__name__, "err_str": str(e)})
TEXT_ANSWER_VALIDATOR_CLASSES = [
RELATEPageValidator,
]
def get_validator_class(location, validator_type):
for validator_class in TEXT_ANSWER_VALIDATOR_CLASSES:
if validator_class.type == validator_type:
return validator_class
raise ValidationError(
string_concat(
"%(location)s: ",
_("unknown validator type"),
"'%(type)s'")
% {"location": location, "type": validator_type})
def parse_validator(vctx, location, validator_desc):
if not isinstance(validator_desc, Struct):
raise ValidationError(
string_concat(
"%s: ",
% location)
if not hasattr(validator_desc, "type"):
raise ValidationError(
string_concat(
"%s: ",
"matcher must supply 'type'")
% location)
return (get_validator_class(location, validator_desc.type)
(vctx, location, validator_desc))
Loading
Loading full blame...