Newer
Older
Andreas Klöckner
committed
from __future__ import division, unicode_literals
__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.db import models
from django.utils.timezone import now
from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.utils.translation import (
ugettext_lazy as _, pgettext_lazy, string_concat)
from django.db.models.signals import post_save
from django.dispatch import receiver
ifaint
committed
from course.constants import ( # noqa
user_status, USER_STATUS_CHOICES,
participation_role, PARTICIPATION_ROLE_CHOICES,
participation_status, PARTICIPATION_STATUS_CHOICES,
flow_permission, FLOW_PERMISSION_CHOICES,
flow_session_expiration_mode, FLOW_SESSION_EXPIRATION_MODE_CHOICES,
grade_aggregation_strategy, GRADE_AGGREGATION_STRATEGY_CHOICES,
grade_state_change_types, GRADE_STATE_CHANGE_CHOICES,
flow_rule_kind, FLOW_RULE_KIND_CHOICES,
exam_ticket_states, EXAM_TICKET_STATE_CHOICES,
participation_permission, PARTICIPATION_PERMISSION_CHOICES,
from yamlfield.fields import YAMLField
identifier = models.CharField(max_length=200, unique=True,
help_text=_("A course identifier. Alphanumeric with dashes, "
"no spaces. This is visible in URLs and determines the location "
"on your file system where the course's git repository lives. "
"This should <em>not</em> be changed after the course has been created "
"without also moving the course's git on the server."),
db_index=True,
validators=[
RegexValidator(
"^"+COURSE_ID_REGEX+"$",
message=_(
"Identifier may only contain letters, "
"numbers, and hypens ('-').")),
]
)
name = models.CharField(
null=True, blank=False,
max_length=200,
verbose_name=_('Course name'),
help_text=_("A human-readable name for the course. "
"(e.g. 'Numerical Methods')"))
number = models.CharField(
null=True, blank=False,
max_length=200,
verbose_name=_('Course number'),
help_text=_("A human-readable course number/ID "
"for the course (e.g. 'CS123')"))
time_period = models.CharField(
null=True, blank=False,
max_length=200,
verbose_name=_('Time Period'),
help_text=_("A human-readable description of the "
"time period for the course (e.g. 'Fall 2014')"))
start_date = models.DateField(
verbose_name=_('Start date'),
null=True, blank=True)
end_date = models.DateField(
verbose_name=_('End date'),
null=True, blank=True)
hidden = models.BooleanField(
default=True,
help_text=_("Is the course only accessible to course staff?"),
verbose_name=_('Only visible to course staff'))
help_text=_("Should the course be listed on the main page?"),
accepts_enrollment = models.BooleanField(
Dong Zhuang
committed
default=True,
verbose_name=_('Accepts enrollment'))
git_source = models.CharField(max_length=200, blank=True,
help_text=_("A Git URL from which to pull course updates. "
"to get some sample content."),
ssh_private_key = models.TextField(blank=True,
help_text=_("An SSH private key to use for Git authentication. "
"Not needed for the sample URL above."
"You may use <a href='/generate-ssh-key'>this tool</a> to generate "
"a key pair."),
course_root_path = models.CharField(max_length=200, blank=True,
help_text=_(
'Subdirectory <em>within</em> the git repository to use as '
'course root directory. Not required, and usually blank. '
'Use only if your course content lives in a subdirectory '
'of your git repository. '
'Should not include trailing slash.'),
verbose_name=_('Course root in repository'))
course_file = models.CharField(max_length=200,
default="course.yml",
help_text=_("Name of a YAML file in the git repository that "
"contains the root course descriptor."),
events_file = models.CharField(max_length=200,
default="events.yml",
help_text=_("Name of a YAML file in the git repository that "
"contains calendar information."),
enrollment_approval_required = models.BooleanField(
help_text=_("If set, each enrolling student must be "
"individually approved."),
verbose_name=_('Enrollment approval required'))
preapproval_require_verified_inst_id = models.BooleanField(
default=True,
help_text=_("If set, students cannot get participation "
"preapproval using institutional ID if "
verbose_name=_('Prevent preapproval by institutional ID if not '
enrollment_required_email_suffix = models.CharField(
max_length=200, blank=True, null=True,
help_text=_("Enrollee's email addresses must end in the "
"specified suffix, such as '@illinois.edu'."),
verbose_name=_('Enrollment required email suffix'))
from_email = models.EmailField(
# Translators: replace "RELATE" with the brand name of your
# website if necessary.
help_text=_("This email address will be used in the 'From' line "
ifaint
committed
"of automated emails sent by RELATE."),
notify_email = models.EmailField(
"notifications about the course."),
# {{{ XMPP
course_xmpp_id = models.CharField(max_length=200, blank=True, null=True,
help_text=_("(Required only if the instant message feature is "
"desired.) The Jabber/XMPP ID (JID) the course will use to sign "
"in to an XMPP server."),
course_xmpp_password = models.CharField(max_length=200, blank=True, null=True,
help_text=_("(Required only if the instant message feature is "
"desired.) The password to go with the JID above."),
recipient_xmpp_id = models.CharField(max_length=200, blank=True, null=True,
help_text=_("(Required only if the instant message feature is "
"desired.) The JID to which instant messages will be sent."),
active_git_commit_sha = models.CharField(max_length=200, null=False,
participants = models.ManyToManyField(settings.AUTH_USER_MODEL,
class Meta:
verbose_name = _("Course")
def __unicode__(self):
return self.identifier
return reverse("relate-course_page", args=(self.identifier,))
class Event(models.Model):
"""An event is an identifier that can be used to specify dates in
verbose_name=_('Course'), on_delete=models.CASCADE)
kind = models.CharField(max_length=50,
# Translators: format of event kind in Event model
help_text=_("Should be lower_case_with_underscores, no spaces "
"allowed."),
ordinal = models.IntegerField(blank=True, null=True,
# Translators: ordinal of event of the same kind
time = models.DateTimeField(verbose_name=_('Start time'))
end_time = models.DateTimeField(null=True, blank=True,
all_day = models.BooleanField(default=False,
# Translators: for when the due time is "All day", how the webpage
# of a event is displayed.
help_text=_("Only affects the rendering in the class calendar, "
shown_in_calendar = models.BooleanField(default=True,
verbose_name = _("Event")
ordering = ("course", "time")
unique_together = (("course", "kind", "ordinal"))
def __unicode__(self):
if self.ordinal is not None:
return "%s %s" % (self.kind, self.ordinal)
else:
return self.kind
# {{{ participation
verbose_name=_('Course'), on_delete=models.CASCADE)
name = models.CharField(max_length=100, unique=True,
help_text=_("Format is lower-case-with-hyphens. "
shown_to_participant = models.BooleanField(default=False,
verbose_name=_('Shown to pariticpant'))
super(ParticipationTag, self).clean()
# Translators: "Name" is the name of a ParticipationTag
raise ValidationError(
{"name": _("Name contains invalid characters.")})
def __unicode__(self):
return "%s (%s)" % (self.name, self.course)
verbose_name = _("Participation tag")
unique_together = (("course", "name"),)
ordering = ("course", "name")
class ParticipationRole(models.Model):
course = models.ForeignKey(Course,
verbose_name=_('Course'), on_delete=models.CASCADE)
identifier = models.CharField(
max_length=100, blank=False, null=False,
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
help_text=_("A symbolic name for this role, used in course code. "
"lower_case_with_underscores, no spaces."),
verbose_name=_('Role identifier'))
name = models.CharField(max_length=200, blank=False, null=False,
help_text=_("A human-readable description of this role."),
verbose_name=_('Role name'))
def clean(self):
super(ParticipationRole, self).clean()
import re
name_valid_re = re.compile(r"^\w+$")
if name_valid_re.match(self.identifier) is None:
# Translators: "Name" is the name of a ParticipationTag
raise ValidationError(
{"name": _("Name contains invalid characters.")})
def __unicode__(self):
return _("%s in %s") % (self.identifier, self.course)
if six.PY3:
__str__ = __unicode__
class Meta:
verbose_name = _("Participation role")
verbose_name_plural = _("Participation roles")
unique_together = (("course", "identifier"),)
ordering = ("course", "identifier")
class ParticipationPermissionBase(models.Model):
permission = models.CharField(max_length=200, blank=False, null=False,
choices=PARTICIPATION_PERMISSION_CHOICES,
verbose_name=_('Permission'))
argument = models.CharField(max_length=200, blank=True, null=True,
verbose_name=_('Argument'))
class Meta:
abstract = True
def __unicode__(self):
if self.argument:
return "%s %s" % (self.permission, self.argument)
if six.PY3:
__str__ = __unicode__
class ParticipationRolePermission(ParticipationPermissionBase):
role = models.ForeignKey(ParticipationRole,
verbose_name=_('Role'), on_delete=models.CASCADE)
class Meta:
verbose_name = _("Participation role permission")
verbose_name_plural = _("Participation role permissions")
unique_together = (("role", "permission", "argument"),)
user = models.ForeignKey(settings.AUTH_USER_MODEL,
verbose_name=_('User ID'), on_delete=models.CASCADE,
related_name="participations")
course = models.ForeignKey(Course, related_name="participations",
verbose_name=_('Course'), on_delete=models.CASCADE)
ifaint
committed
enroll_time = models.DateTimeField(default=now,
help_text=_("Instructors may update course content. "
"Teaching assistants may access and change grade data. "
"Observers may access analytics. "
"Each role includes privileges from subsequent roles."),
roles = models.ManyToManyField(ParticipationRole, blank=True,
verbose_name=_("Roles"))
time_factor = models.DecimalField(
max_digits=10, decimal_places=2,
ifaint
committed
default=1,
help_text=_("Multiplier for time available on time-limited "
preview_git_commit_sha = models.CharField(max_length=200, null=True,
ifaint
committed
tags = models.ManyToManyField(ParticipationTag, blank=True,
# Translators: displayed format of Participation: some user in some
# course as some role
ifaint
committed
return _("%(user)s in %(course)s as %(role)s") % {
"user": self.user, "course": self.course,
"role": dict(PARTICIPATION_ROLE_CHOICES).get(self.role).lower()}
verbose_name = _("Participation")
unique_together = (("user", "course"),)
def get_role_desc(self):
return dict(PARTICIPATION_ROLE_CHOICES).get(
self.role)
class ParticipationPermission(ParticipationPermissionBase):
participation = models.ForeignKey(Participation,
verbose_name=_('Participation'), on_delete=models.CASCADE)
class Meta:
verbose_name = _("Participation permission")
verbose_name_plural = _("Participation permissionss")
unique_together = (("participation", "permission", "argument"),)
class ParticipationPreapproval(models.Model):
email = models.EmailField(max_length=254, null=True, blank=True,
institutional_id = models.CharField(max_length=254, null=True, blank=True,
verbose_name=_('Institutional ID'))
verbose_name=_('Course'), on_delete=models.CASCADE)
role = models.CharField(max_length=50,
creator = models.ForeignKey(settings.AUTH_USER_MODEL, null=True,
Andreas Klöckner
committed
verbose_name=_('Creator'), on_delete=models.SET_NULL)
creation_time = models.DateTimeField(default=now, db_index=True,
# Translators: somebody's email in some course in Participation
# Preapproval
return _("Email %(email)s in %(course)s") % {
"email": self.email, "course": self.course}
elif self.institutional_id:
# Translators: somebody's Institutional ID in some course in
# Participation Preapproval
return _("Institutional ID %(inst_id)s in %(course)s") % {
"inst_id": self.institutional_id, "course": self.course}
verbose_name = _("Participation preapproval")
verbose_name_plural = _("Participation preapprovals")
unique_together = (("course", "email"),)
ordering = ("course", "email")
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
def add_default_roles_and_permissions(course,
role_model=ParticipationRole,
role_permission_model=ParticipationRolePermission):
from course.constants import participation_permission as pp
rpm = role_permission_model
def add_teaching_assistant_permissions(role):
rpm(role=role, permission=pp.impersonate_role).save()
rpm(role=role, permission=pp.issue_exam_ticket).save()
rpm(role=role, permission=pp.see_flow_sessions_from_role,
argument="student").save()
rpm(role=role, permission=pp.see_grades_from_role,
argument="student").save()
rpm(role=role, permission=pp.see_gradebook).save()
rpm(role=role, permission=pp.assign_grade).save()
rpm(role=role, permission=pp.see_grader_stats).save()
rpm(role=role, permission=pp.impose_deadline).save()
rpm(role=role, permission=pp.regrade_flow).save()
rpm(role=role, permission=pp.add_exception).save()
rpm(role=role, permission=pp.see_analytics).save()
rpm(role=role, permission=pp.preview_content).save()
rpm(role=role, permission=pp.use_markup_sandbox).save()
rpm(role=role, permission=pp.use_page_sandbox).save()
rpm(role=role, permission=pp.test_flow).save()
rpm(role=role, permission=pp.query_participation).save()
def add_instructor_permisisons(role):
rpm(role=role, permission=pp.edit_course).save()
rpm(role=role, permission=pp.edit_exam).save()
rpm(role=role, permission=pp.batch_issue_exam_ticket).save()
rpm(role=role, permission=pp.see_flow_sessions_from_role,
argument="teaching_assistant").save()
rpm(role=role, permission=pp.see_grades_from_role,
argument="teaching_assistant").save()
rpm(role=role, permission=pp.batch_import_grade).save()
rpm(role=role, permission=pp.batch_export_grade).save()
rpm(role=role, permission=pp.update_content).save()
rpm(role=role, permission=pp.edit_events).save()
rpm(role=role, permission=pp.manage_instant_flow_requests).save()
rpm(role=role, permission=pp.preapprove_participation).save()
add_teaching_assistant_permissions(role)
instructor = role_model(
course=course, identifier="instructor",
name=_("Instructor"))
instructor.save()
teaching_assistant = role_model(
course=course, identifier="teaching_assistant",
name=_("Teaching Assistant"))
teaching_assistant.save()
student = role_model(
course=course, identifier="student",
name=_("Student"))
student.save()
unenrolled = role_model(
course=course, identifier="unenrolled",
name=_("Unenrolled"))
unenrolled.save()
add_teaching_assistant_permissions(teaching_assistant)
add_instructor_permisisons(instructor)
@receiver(post_save, sender=Course, dispatch_uid="add_default_permissions")
def _set_up_course_permissions(sender, course, created, raw, using, update_fields,
**kwargs):
if created:
add_default_roles_and_permissions(course)
# {{{ instant flow request
verbose_name=_('Course'), on_delete=models.CASCADE)
class Meta:
verbose_name = _("Instant flow request")
verbose_name_plural = _("Instant flow requests")
def __unicode__(self):
return _("Instant flow request for "
"%(flow_id)s in %(course)s at %(start_time)s") \
% {
"flow_id": self.flow_id,
"course": self.course,
"start_time": self.start_time,
}
if six.PY3:
__str__ = __unicode__
class FlowSession(models.Model):
# This looks like it's redundant with 'participation', below--but it's not.
# 'participation' is nullable.
verbose_name=_('Course'), on_delete=models.CASCADE)
participation = models.ForeignKey(Participation, null=True, blank=True,
db_index=True, related_name="flow_sessions",
verbose_name=_('Participation'), on_delete=models.CASCADE)
Andreas Klöckner
committed
# This looks like it's redundant with participation, above--but it's not.
# Again--'participation' is nullable, and it is useful to be able to
# remember what user a session belongs to, even if they're not enrolled.
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True,
Andreas Klöckner
committed
verbose_name=_('User'), on_delete=models.SET_NULL)
Andreas Klöckner
committed
active_git_commit_sha = models.CharField(max_length=200,
flow_id = models.CharField(max_length=200, db_index=True,
completion_time = models.DateTimeField(null=True, blank=True,
page_count = models.IntegerField(null=True, blank=True,
# This field allows avoiding redundant checks for whether the
# page data is in line with the course material and the current
# version of RELATE.
# See course.flow.adjust_flow_session_page_data.
page_data_at_revision_key = models.CharField(
max_length=200, null=True, blank=True,
verbose_name=_('Page data at course revision'),
help_text=_(
"Page set-up data is up-to date for this revision of the "
"course material"))
access_rules_tag = models.CharField(max_length=200, null=True,
verbose_name=_('Access rules tag'))
expiration_mode = models.CharField(max_length=20, null=True,
# Non-normal: These fields can be recomputed, albeit at great expense.
#
# Looking up the corresponding GradeChange is also invalid because
# some flow sessions are not for credit and still have results.
points = models.DecimalField(max_digits=10, decimal_places=2,
max_points = models.DecimalField(max_digits=10, decimal_places=2,
result_comment = models.TextField(blank=True, null=True,
verbose_name = _("Flow session")
def __unicode__(self):
if self.participation is None:
ifaint
committed
return _("anonymous session %(session_id)d on '%(flow_id)s'") % {
'session_id': self.id,
'flow_id': self.flow_id}
ifaint
committed
return _("%(user)s's session %(session_id)d on '%(flow_id)s'") % {
'user': self.participation.user,
'session_id': self.id,
'flow_id': self.flow_id}
def append_comment(self, s):
if s is None:
return
if self.result_comment:
self.result_comment += "\n" + s
else:
self.result_comment = s
def points_percentage(self):
if self.points is None:
return None
elif self.max_points:
return 100*self.points/self.max_points
else:
return None
def answer_visits(self):
# only use this from templates
from course.flow import assemble_answer_visits
return assemble_answer_visits(self)
def last_activity(self):
for visit in (FlowPageVisit.objects
.filter(
flow_session=self,
is_synthetic=False)
.order_by("-visit_time")
[:1]):
return visit.visit_time
return None
def get_expiration_mode_desc(self):
return dict(FLOW_SESSION_EXPIRATION_MODE_CHOICES).get(
self.expiration_mode)
# }}}
# {{{ flow page data
class FlowPageData(models.Model):
flow_session = models.ForeignKey(FlowSession, related_name="page_data",
verbose_name=_('Flow session'), on_delete=models.CASCADE)
ordinal = models.IntegerField(null=True, blank=True,
# This exists to catch changing page types in course content,
# which will generally lead to an inconsistency disaster.
page_type = models.CharField(max_length=200,
verbose_name=_('Page type as indicated in course content'),
null=True, blank=True)
ifaint
committed
# Show correct characters in admin for non ascii languages.
dump_kwargs={'ensure_ascii': False},
title = models.CharField(max_length=1000,
verbose_name=_('Page Title'), null=True, blank=True)
bookmarked = models.BooleanField(default=False,
help_text=_("A user-facing 'marking' feature to allow participants to "
"easily return to pages that still need their attention."),
verbose_name=_('Bookmarked'))
verbose_name = _("Flow page data")
verbose_name_plural = _("Flow page data")
return (_("Data for page '%(group_id)s/%(page_id)s' "
"(ordinal %(ordinal)s) in %(flow_session)s") % {
'group_id': self.group_id,
'page_id': self.page_id,
'ordinal': self.ordinal,
'flow_session': self.flow_session})
# Django's templates are a little daft. No arithmetic--really?
def previous_ordinal(self):
return self.ordinal - 1
def next_ordinal(self):
return self.ordinal + 1
def human_readable_ordinal(self):
return self.ordinal + 1
# }}}
# {{{ flow page visit
class FlowPageVisit(models.Model):
# This is redundant (because the FlowSession is available through
# page_data), but it helps the admin site understand the link
# and provide editing.
flow_session = models.ForeignKey(FlowSession, db_index=True,
verbose_name=_('Flow session'), on_delete=models.CASCADE)
page_data = models.ForeignKey(FlowPageData, db_index=True,
verbose_name=_('Page data'), on_delete=models.CASCADE)
visit_time = models.DateTimeField(default=now, db_index=True,
remote_address = models.GenericIPAddressField(null=True, blank=True,
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True,
blank=True, related_name="visitor",
Andreas Klöckner
committed
verbose_name=_('User'), on_delete=models.SET_NULL)
impersonated_by = models.ForeignKey(settings.AUTH_USER_MODEL,
null=True, blank=True, related_name="impersonator",
Andreas Klöckner
committed
verbose_name=_('Impersonated by'), on_delete=models.SET_NULL)
is_synthetic = models.BooleanField(default=False,
help_text=_("Synthetic flow page visits are generated for "
"unvisited pages once a flow is finished. This is needed "
"since grade information is attached to a visit, and it "
"needs a place to go."),
verbose_name=_('Is synthetic'))
ifaint
committed
# Show correct characters in admin for non ascii languages.
dump_kwargs={'ensure_ascii': False},
# is_submitted_answer may seem redundant with answers being
# non-NULL, but it isn't. This supports saved (but as
# yet ungraded) answers.
# NULL means it's not an answer at all.
# (Should coincide with 'answer is None')
# True means it's a final, submitted answer fit for grading.
# False means it's just a saved answer.
# Translators: determine whether the answer is a final,
# submitted answer fit for grading.
# Translators: flow page visit
_("'%(group_id)s/%(page_id)s' in '%(session)s' "
"on %(time)s")
% {"group_id": self.page_data.group_id,
"page_id": self.page_data.page_id,
"session": self.flow_session,
"time": self.visit_time})
result += six.text_type(_(" (with answer)"))
return result
# These must be distinguishable, to figure out what came later.
unique_together = (("page_data", "visit_time"),)
def get_most_recent_grade(self):
grades = self.grades.order_by("-grade_time")[:1]
for grade in grades:
return grade
return None
def get_most_recent_feedback(self):
grade = self.get_most_recent_grade()
if grade is None:
return None
else:
return get_feedback_for_grade(grade)
def is_impersonated(self):
if self.impersonated_by:
return True
else:
return False
# }}}
# {{{ flow page visit grade
class FlowPageVisitGrade(models.Model):
visit = models.ForeignKey(FlowPageVisit, related_name="grades",
verbose_name=_('Visit'), on_delete=models.CASCADE)
# NULL means 'autograded'
grader = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True,
Andreas Klöckner
committed
verbose_name=_('Grader'), on_delete=models.SET_NULL)
grade_time = models.DateTimeField(db_index=True, default=now,
graded_at_git_commit_sha = models.CharField(
ifaint
committed
# Show correct characters in admin for non ascii languages.
dump_kwargs={'ensure_ascii': False},
# This data should be recomputable, but we'll cache it here,
# because it might be very expensive (container-launch expensive
# for code questions, for example) to recompute.
max_points = models.FloatField(null=True, blank=True,
ifaint
committed
# Translators: max point in grade
help_text=_("Point value of this question when receiving "
correctness = models.FloatField(null=True, blank=True,
ifaint
committed
# Translators: correctness in grade
help_text=_("Real number between zero and one (inclusively) "
"indicating the degree of correctness of the answer."),
# This JSON object has fields corresponding to
# :class:`course.page.AnswerFeedback`, except for
# :attr:`course.page.AnswerFeedback.correctness`, which is stored
# separately for efficiency.
ifaint
committed
# Show correct characters in admin for non ascii languages.
dump_kwargs={'ensure_ascii': False},
# Translators: "Feedback" stands for the feedback of answers.
def percentage(self):
if self.correctness is not None:
return 100*self.correctness
else:
return None
def value(self):
if self.correctness is not None and self.max_points is not None:
return self.correctness * self.max_points
else:
return None
class Meta:
verbose_name_plural = _("Flow page visit grades")
# These must be distinguishable, to figure out what came later.
unique_together = (("visit", "grade_time"),)
ordering = ("visit", "grade_time")
# information on FlowPageVisitGrade class
# Translators: return the information of the grade of a user
# by percentage.
ifaint
committed
return _("grade of %(visit)s: %(percentage)s") % {
"visit": self.visit, "percentage": self.percentage()}
class FlowPageBulkFeedback(models.Model):
# We're only storing one of these per page, because
# they're 'bulk' (i.e. big, like plots or program output)
verbose_name=_('Page data'), on_delete=models.CASCADE)
verbose_name=_('Grade'), on_delete=models.CASCADE)
ifaint
committed
# Show correct characters in admin for non ascii languages.
dump_kwargs={'ensure_ascii': False},
def update_bulk_feedback(page_data, grade, bulk_feedback_json):
FlowPageBulkFeedback.objects.update_or_create(
page_data=page_data,
defaults=dict(
grade=grade,
bulk_feedback=bulk_feedback_json))
def get_feedback_for_grade(grade):
try:
bulk_feedback_json = FlowPageBulkFeedback.objects.get(
page_data=grade.visit.page_data,
grade=grade).bulk_feedback
except ObjectDoesNotExist:
bulk_feedback_json = None
from course.page import AnswerFeedback
if grade is not None:
return AnswerFeedback.from_json(
grade.feedback, bulk_feedback_json)
else:
return None
def validate_stipulations(stip):
if stip is None:
return
if not isinstance(stip, dict):
raise ValidationError(_("stipulations must be a dictionary"))
allowed_keys = set(["credit_percent", "allowed_session_count"])
if not set(stip.keys()) <= allowed_keys:
raise ValidationError(
string_concat(
_("unrecognized keys in stipulations"),