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.
"""
from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now
from django.core.urlresolvers import reverse
from django.core.exceptions import ValidationError, ObjectDoesNotExist
Dong Zhuang
committed
from django.utils.translation import (
ugettext_lazy as _ ,
pgettext_lazy,
ugettext_noop,
string_concat,
ugettext,
)
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,
from yamlfield.fields import YAMLField
# {{{ facility
class Facility(models.Model):
"""Data about a facility from where content may be accessed."""
identifier = models.CharField(max_length=50, unique=True,
help_text="Format is lower-case-with-hyphens. "
Dong Zhuang
committed
"Do not use spaces.",
Dong Zhuang
committed
description = models.CharField(max_length=100,
Dong Zhuang
committed
verbose_name = "Facility"
verbose_name_plural = "Facilities"
def __unicode__(self):
return self.identifier
class FacilityIPRange(models.Model):
"""Network data about a facility from where content may be accessed."""
facility = models.ForeignKey(Facility, related_name="ip_ranges")
ip_range = models.CharField(
max_length=200,
Dong Zhuang
committed
verbose_name="IP range")
Dong Zhuang
committed
description = models.CharField(max_length=100,
Dong Zhuang
committed
verbose_name = "Facility IP range"
def clean(self):
import ipaddr
try:
ipaddr.IPNetwork(self.ip_range)
except Exception as e:
raise ValidationError({"ip_range": str(e)})
# }}}
def get_user_status(user):
try:
return user.user_status
except AttributeError:
ustatus = UserStatus()
ustatus.user = user
ustatus.status = user_status.unconfirmed
ustatus.save()
return ustatus
Dong Zhuang
committed
user = models.OneToOneField(User, db_index=True, related_name="user_status",
Dong Zhuang
committed
choices=USER_STATUS_CHOICES,
sign_in_key = models.CharField(max_length=50,
Dong Zhuang
committed
null=True, unique=True, db_index=True, blank=True,
Dong Zhuang
committed
key_time = models.DateTimeField(default=now,
help_text="The time stamp of the sign in token.",
verbose_name='Key time')
Andreas Klöckner
committed
editor_mode = models.CharField(max_length=20,
choices=(
("default", "Default"),
("sublime", "Sublime text"),
("emacs", "Emacs"),
("vim", "Vim"),
),
Dong Zhuang
committed
default="default",
# Translators: the text editor used by participants
Andreas Klöckner
committed
Dong Zhuang
committed
verbose_name = "User status"
verbose_name_plural = "User statuses"
ordering = ("key_time",)
Dong Zhuang
committed
return "User status for %(user)s" % {'user':self.user}
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.",
hidden = models.BooleanField(
default=True,
Dong Zhuang
committed
help_text="Is the course only accessible to course staff?",
Dong Zhuang
committed
help_text="Should the course be listed on the main page?",
accepts_enrollment = models.BooleanField(
Dong Zhuang
committed
default=True,
valid = models.BooleanField(
default=True,
Dong Zhuang
committed
help_text="Whether the course content has passed validation.",
git_source = models.CharField(max_length=200, blank=True,
help_text="A Git URL from which to pull course updates. "
"If you're just starting out, enter "
Dong Zhuang
committed
"to get some sample content.",
ssh_private_key = models.TextField(blank=True,
help_text="An SSH private key to use for Git authentication. "
Dong Zhuang
committed
"Not needed for the sample URL above.",
course_file = models.CharField(max_length=200,
default="course.yml",
help_text="Name of a YAML file in the git repository that contains "
Dong Zhuang
committed
"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 "
Dong Zhuang
committed
"calendar information.",
enrollment_approval_required = models.BooleanField(
default=False,
help_text="If set, each enrolling student must be "
Dong Zhuang
committed
"individually approved.",
enrollment_required_email_suffix = models.CharField(
max_length=200, blank=True, null=True,
help_text="Enrollee's email addresses must end in the "
Dong Zhuang
committed
"specified suffix, such as '@illinois.edu'.",
from_email = models.EmailField(
help_text="This email address will be used in the 'From' line "
Dong Zhuang
committed
"of automated emails sent by RELATE."),
notify_email = models.EmailField(
help_text="This email address will receive "
Dong Zhuang
committed
"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 "
Dong Zhuang
committed
"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.) "
Dong Zhuang
committed
"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.) "
Dong Zhuang
committed
"The JID to which instant messages will be sent.",
active_git_commit_sha = models.CharField(max_length=200, null=False,
Dong Zhuang
committed
blank=False,
participants = models.ManyToManyField(User,
through='Participation')
Dong Zhuang
committed
class Meta:
verbose_name = "Course"
verbose_name_plural = "Courses"
def __unicode__(self):
return self.identifier
def get_absolute_url(self):
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
Dong Zhuang
committed
course = models.ForeignKey(Course,
kind = models.CharField(max_length=50,
Dong Zhuang
committed
help_text="Should be lower_case_with_underscores, no spaces allowed.",
Dong Zhuang
committed
ordinal = models.IntegerField(blank=True, null=True,
Dong Zhuang
committed
Dong Zhuang
committed
end_time = models.DateTimeField(null=True, blank=True,
all_day = models.BooleanField(default=False,
Dong Zhuang
committed
# 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, "
Dong Zhuang
committed
"in that a start time is not shown",
Dong Zhuang
committed
shown_in_calendar = models.BooleanField(default=True,
Dong Zhuang
committed
verbose_name = "Event"
verbose_name_plural = "Events"
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
Dong Zhuang
committed
course = models.ForeignKey(Course,
name = models.CharField(max_length=100, unique=True,
help_text="Format is lower-case-with-hyphens. "
Dong Zhuang
committed
"Do not use spaces.",
Dong Zhuang
committed
# 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)
class Meta:
Dong Zhuang
committed
verbose_name = "Participation tag"
verbose_name_plural = "Participation tags"
unique_together = (("course", "name"),)
ordering = ("course", "name")
Dong Zhuang
committed
user = models.ForeignKey(User,
Dong Zhuang
committed
course = models.ForeignKey(Course, related_name="participations",
Dong Zhuang
committed
enroll_time = models.DateTimeField(default=now,
choices=PARTICIPATION_ROLE_CHOICES,
help_text="Instructors may update course content. "
"Teaching assistants may access and change grade data. "
"Observers may access analytics. "
Dong Zhuang
committed
"Each role includes privileges from subsequent roles.",
Dong Zhuang
committed
choices=PARTICIPATION_STATUS_CHOICES,
time_factor = models.DecimalField(
max_digits=10, decimal_places=2,
Dong Zhuang
committed
default=1,
help_text="Multiplier for time available on time-limited "
"flows (time-limited flows are currently unimplemented).",
verbose_name='Time factor')
preview_git_commit_sha = models.CharField(max_length=200, null=True,
Dong Zhuang
committed
blank=True,
Dong Zhuang
committed
tags = models.ManyToManyField(ParticipationTag, blank=True,
help_text="NEED HELP TEXT",
Dong Zhuang
committed
# Translators: displayed format of Participation: some user in some course as some role
return "%(user)s in %(course)s as %(role)s" % {
'user':self.user, 'course':self.course, 'role':dict(PARTICIPATION_ROLE_CHOICES).get(self.role).lower()}
Dong Zhuang
committed
verbose_name = "Participation"
verbose_name_plural = "Participations"
unique_together = (("user", "course"),)
class ParticipationPreapproval(models.Model):
Dong Zhuang
committed
email = models.EmailField(max_length=254,
Dong Zhuang
committed
course = models.ForeignKey(Course,
role = models.CharField(max_length=50,
Dong Zhuang
committed
choices=PARTICIPATION_ROLE_CHOICES,
Dong Zhuang
committed
creator = models.ForeignKey(User, null=True,
Dong Zhuang
committed
creation_time = models.DateTimeField(default=now, db_index=True,
Dong Zhuang
committed
# Translators: somebody's email in some course in Particiaption Preapproval
return "%(email)s in %(course)s" % {"email": self.email, "course": self.course}
Dong Zhuang
committed
verbose_name = "Participation preapproval"
verbose_name_plural = "Participation preapprovals"
unique_together = (("course", "email"),)
ordering = ("course", "email")
Dong Zhuang
committed
course = models.ForeignKey(Course,
Dong Zhuang
committed
flow_id = models.CharField(max_length=200,
Dong Zhuang
committed
start_time = models.DateTimeField(default=now,
Dong Zhuang
committed
end_time = models.DateTimeField(
Dong Zhuang
committed
cancelled = models.BooleanField(default=False,
Dong Zhuang
committed
class Meta:
verbose_name = "Instant flow request"
verbose_name_plural = "Instant flow requests"
class FlowSession(models.Model):
# This looks like it's redundant with 'participation', below--but it's not.
# 'participation' is nullable.
Dong Zhuang
committed
course = models.ForeignKey(Course,
participation = models.ForeignKey(Participation, null=True, blank=True,
Dong Zhuang
committed
db_index=True,
Dong Zhuang
committed
active_git_commit_sha = models.CharField(max_length=200,
Dong Zhuang
committed
flow_id = models.CharField(max_length=200, db_index=True,
Dong Zhuang
committed
start_time = models.DateTimeField(default=now,
Dong Zhuang
committed
completion_time = models.DateTimeField(null=True, blank=True,
Dong Zhuang
committed
page_count = models.IntegerField(null=True, blank=True,
Dong Zhuang
committed
in_progress = models.BooleanField(default=None,
access_rules_tag = models.CharField(max_length=200, null=True,
Dong Zhuang
committed
blank=True,
expiration_mode = models.CharField(max_length=20, null=True,
Dong Zhuang
committed
choices=FLOW_SESSION_EXPIRATION_MODE_CHOICES,
# 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,
Dong Zhuang
committed
blank=True, null=True,
max_points = models.DecimalField(max_digits=10, decimal_places=2,
Dong Zhuang
committed
blank=True, null=True,
Dong Zhuang
committed
result_comment = models.TextField(blank=True, null=True,
Dong Zhuang
committed
verbose_name = "Flow session"
verbose_name_plural = "Flow sessions"
def __unicode__(self):
if self.participation is None:
Dong Zhuang
committed
return "anonymous session %(session_id)d on '%(flow_id)s'" % {
'session_id':self.id,
'flow_id':self.flow_id}
Dong Zhuang
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
# }}}
# {{{ flow page data
class FlowPageData(models.Model):
Dong Zhuang
committed
flow_session = models.ForeignKey(FlowSession, related_name="page_data",
Dong Zhuang
committed
ordinal = models.IntegerField(null=True, blank=True,
Dong Zhuang
committed
group_id = models.CharField(max_length=200,
Dong Zhuang
committed
page_id = models.CharField(max_length=200,
Dong Zhuang
committed
data = JSONField(null=True, blank=True,
# Show correct characters in admin for non ascii languages.
dump_kwargs={'ensure_ascii': False},
Dong Zhuang
committed
verbose_name = "Flow page data"
verbose_name_plural = "Flow page data"
Dong Zhuang
committed
# 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
# }}}
# {{{ 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.
Dong Zhuang
committed
flow_session = models.ForeignKey(FlowSession, db_index=True,
Dong Zhuang
committed
page_data = models.ForeignKey(FlowPageData, db_index=True,
Dong Zhuang
committed
visit_time = models.DateTimeField(default=now, db_index=True,
Dong Zhuang
committed
remote_address = models.GenericIPAddressField(null=True, blank=True,
Dong Zhuang
committed
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')
Dong Zhuang
committed
answer = JSONField(null=True, blank=True,
# Show correct characters in admin for non ascii languages.
dump_kwargs={'ensure_ascii': False},
# Translators: "Answer" is a Noun.
# 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.
Dong Zhuang
committed
is_submitted_answer = models.NullBooleanField(
# Translators: determine whether the answer is a final, submitted answer fit for grading.
Dong Zhuang
committed
# Translators: flow page visit
result = "'%(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}
Dong Zhuang
committed
# Translators: flow page visit: if the answer is provided by user then append the string.
result += unicode(" (with answer)")
return result
Dong Zhuang
committed
verbose_name = "Flow page visit"
# 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)
# }}}
# {{{ flow page visit grade
class FlowPageVisitGrade(models.Model):
Dong Zhuang
committed
visit = models.ForeignKey(FlowPageVisit, related_name="grades",
# NULL means 'autograded'
Dong Zhuang
committed
grader = models.ForeignKey(User, null=True, blank=True,
Dong Zhuang
committed
grade_time = models.DateTimeField(db_index=True, default=now,
graded_at_git_commit_sha = models.CharField(
Dong Zhuang
committed
max_length=200, null=True, blank=True,
Dong Zhuang
committed
grade_data = JSONField(null=True, blank=True,
# 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,
Dong Zhuang
committed
# Translators: max point in grade
help_text="Point value of this question when receiving "
Dong Zhuang
committed
"full credit.",
correctness = models.FloatField(null=True, blank=True,
Dong Zhuang
committed
# Translators: correctness in grade
help_text="Real number between zero and one (inclusively) "
Dong Zhuang
committed
"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.
Dong Zhuang
committed
feedback = JSONField(null=True, blank=True,
# 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:
Dong Zhuang
committed
verbose_name = "Flow page visit grade"
# These must be distinguishable, to figure out what came later.
unique_together = (("visit", "grade_time"),)
ordering = ("visit", "grade_time")
Dong Zhuang
committed
# information on FlowPageVisitGrade class
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)
Dong Zhuang
committed
page_data = models.OneToOneField(FlowPageData,
Dong Zhuang
committed
grade = models.ForeignKey(FlowPageVisitGrade,
Dong Zhuang
committed
bulk_feedback = JSONField(null=True, blank=True,
# 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("unrecognized keys in stipulations: %s"
% ", ".join(set(stip.keys()) - allowed_keys))
if "credit_percent" in stip and not isinstance(
stip["credit_percent"], (int, float)):
raise ValidationError("credit_percent must be a float")
if ("allowed_session_count" in stip
and (
not isinstance(stip["allowed_session_count"], int)
or stip["allowed_session_count"] < 0)):
raise ValidationError("allowed_session_count must be a non-negative integer")
# {{{ deprecated exception stuff
class FlowAccessException(models.Model):
Dong Zhuang
committed
participation = models.ForeignKey(Participation, db_index=True,
Dong Zhuang
committed
flow_id = models.CharField(max_length=200, blank=False, null=False,
Dong Zhuang
committed
expiration = models.DateTimeField(blank=True, null=True,
stipulations = JSONField(blank=True, null=True,
Dong Zhuang
committed
# Translators: help text for stipulations in FlowAccessException (deprecated)
help_text="A dictionary of the same things that can be added "
"to a flow access rule, such as allowed_session_count or "
"credit_percent. If not specified here, values will default "
"to the stipulations in the course content.",
Dong Zhuang
committed
validators=[validate_stipulations],
dump_kwargs={'ensure_ascii': False},
Dong Zhuang
committed
creator = models.ForeignKey(User, null=True,
Dong Zhuang
committed
creation_time = models.DateTimeField(default=now, db_index=True,
is_sticky = models.BooleanField(
default=False,
Dong Zhuang
committed
# Translators: deprecated
help_text="Check if a flow started under this "
"exception rule set should stay "
Dong Zhuang
committed
"under this rule set until it is expired.",
# Translators: deprecated
Dong Zhuang
committed
comment = models.TextField(blank=True, null=True,
Dong Zhuang
committed
# Translators: flow access exception in admin (deprecated)
return "Access exception for '%(user)s' to '%(flow_id)s' in '%(course)s'" % {
'user':self.participation.user, 'flow_id':self.flow_id,
'course':self.participation.course}
class FlowAccessExceptionEntry(models.Model):
exception = models.ForeignKey(FlowAccessException,
Dong Zhuang
committed
related_name="entries",
permission = models.CharField(max_length=50,
Dong Zhuang
committed
choices=FLOW_PERMISSION_CHOICES,
Dong Zhuang
committed
# Translators: FlowAccessExceptionEntry (deprecated)
verbose_name_plural = "Flow access exception entries"
def __unicode__(self):
return self.permission
# }}}
class FlowRuleException(models.Model):
Dong Zhuang
committed
flow_id = models.CharField(max_length=200, blank=False, null=False,
Dong Zhuang
committed
participation = models.ForeignKey(Participation, db_index=True,
Dong Zhuang
committed
expiration = models.DateTimeField(blank=True, null=True,
Dong Zhuang
committed
creator = models.ForeignKey(User, null=True,
Dong Zhuang
committed
creation_time = models.DateTimeField(default=now, db_index=True,
Dong Zhuang
committed
comment = models.TextField(blank=True, null=True,
kind = models.CharField(max_length=50, blank=False, null=False,
Dong Zhuang
committed
choices=FLOW_RULE_KIND_CHOICES,
Dong Zhuang
committed
rule = YAMLField(blank=False, null=False,
Dong Zhuang
committed
active = models.BooleanField(default=True,
verbose_name=pgettext_lazy("is the flow rule exception activated?", "Active"))
def __unicode__(self):
Dong Zhuang
committed
# Translators: For FlowRuleException
return "%(kind)s exception for '%(user)s' to '%(flow_id)s' in '%(course)s'" % {
'kind':self.kind,
'user':self.participation.user, 'flow_id':self.flow_id,
'course':self.participation.course}
def clean(self):
if (self.kind == flow_rule_kind.grading
and self.expiration is not None):
raise ValidationError("grading rules may not expire")
from course.validation import (
ValidationError as ContentValidationError,
validate_session_start_rule,
validate_session_access_rule,
validate_session_grading_rule,
ValidationContext)
from course.content import (get_course_repo,
get_course_commit_sha,
get_flow_desc)
rule = dict_to_struct(self.rule)
repo = get_course_repo(self.participation.course)
commit_sha = get_course_commit_sha(
self.participation.course, self.participation)
ctx = ValidationContext(
repo=repo,
commit_sha=commit_sha)
flow_desc = get_flow_desc(repo,
self.participation.course,
self.flow_id, commit_sha)
tags = None
if hasattr(flow_desc, "rules"):
tags = getattr(flow_desc.rules, "tags", None)
try:
if self.kind == flow_rule_kind.start:
validate_session_start_rule(ctx, unicode(self), rule, tags)
elif self.kind == flow_rule_kind.access:
validate_session_access_rule(ctx, unicode(self), rule, tags)
elif self.kind == flow_rule_kind.grading:
validate_session_grading_rule(ctx, unicode(self), rule, tags)
else:
Dong Zhuang
committed
# the rule refers to FlowRuleException rule
raise ValidationError("invalid rule kind: "+self.kind)
except ContentValidationError as e:
Dong Zhuang
committed
# the rule refers to FlowRuleException rule
raise ValidationError("invalid existing_session_rules: "+str(e))
Dong Zhuang
committed
class Meta:
verbose_name = "Flow rule exception"
Dong Zhuang
committed
# }}}
# {{{ grading
class GradingOpportunity(models.Model):
Dong Zhuang
committed
course = models.ForeignKey(Course,
identifier = models.CharField(max_length=200, blank=False, null=False,
Dong Zhuang
committed
# Translators: format of identifier for GradingOpportunity
help_text="A symbolic name for this grade. "
Dong Zhuang
committed
"lower_case_with_underscores, no spaces.",
name = models.CharField(max_length=200, blank=False, null=False,
Dong Zhuang
committed
# Translators: name for GradingOpportunity
help_text="A human-readable identifier for the grade.",
flow_id = models.CharField(max_length=200, blank=True, null=True,
help_text="Flow identifier that this grading opportunity "
Dong Zhuang
committed
"is linked to, if any",
aggregation_strategy = models.CharField(max_length=20,
Dong Zhuang
committed
choices=GRADE_AGGREGATION_STRATEGY_CHOICES,
# Translators: strategy on how the grading of mutiple sessioins are aggregated.
Dong Zhuang
committed
due_time = models.DateTimeField(default=None, blank=True, null=True,
Dong Zhuang
committed
creation_time = models.DateTimeField(default=now,
Dong Zhuang
committed
shown_in_grade_book = models.BooleanField(default=True,
Dong Zhuang
committed
shown_in_student_grade_book = models.BooleanField(default=True,
Dong Zhuang
committed
verbose_name = "Grading opportunity"
verbose_name_plural = "Grading opportunities"
ordering = ("course", "due_time", "identifier")
unique_together = (("course", "identifier"),)
def __unicode__(self):
Dong Zhuang
committed
# Translators: For GradingOpportunity
return "%(opportunity_name)s (%(opportunity_id)s) in %(course)s" % {
'opportunity_name':self.name, 'opportunity_id':self.identifier, 'course':self.course}
class GradeChange(models.Model):
"""Per 'grading opportunity', each participant may accumulate multiple grades
that are aggregated according to :attr:`GradingOpportunity.aggregation_strategy`.
In addition, for each opportunity, grade changes are grouped by their 'attempt'
identifier, where later grades with the same :attr:`attempt_id` supersede earlier
ones.
"""
Dong Zhuang
committed
opportunity = models.ForeignKey(GradingOpportunity,
Dong Zhuang
committed
participation = models.ForeignKey(Participation,
state = models.CharField(max_length=50,
Dong Zhuang
committed
choices=GRADE_STATE_CHANGE_CHOICES,
# Translators: something like 'status'.
attempt_id = models.CharField(max_length=50, null=True, blank=True,
Dong Zhuang
committed
# Translators: help text of "attempt_id" in GradeChange class
help_text="Grade changes are grouped by their 'attempt ID' "
"where later grades with the same attempt ID supersede earlier "
Dong Zhuang
committed
"ones.",
points = models.DecimalField(max_digits=10, decimal_places=2,
Dong Zhuang
committed
blank=True, null=True,