Commit b2e7be92 by Will Daly

Migrate submissions app from the edx-ora2 repository

parent 7d98d907
from django.contrib import admin
from django.core.urlresolvers import reverse
from django.utils import html
from submissions.models import Score, ScoreSummary, StudentItem, Submission
class StudentItemAdminMixin(object):
"""Mix this class into anything that has a student_item fkey."""
search_fields = (
'student_item__course_id',
'student_item__student_id',
'student_item__item_id',
'student_item__id'
)
def course_id(self, obj):
return obj.student_item.course_id
course_id.admin_order_field = 'student_item__course_id'
def item_id(self, obj):
return obj.student_item.item_id
item_id.admin_order_field = 'student_item__item_id'
def student_id(self, obj):
return obj.student_item.student_id
student_id.admin_order_field = 'student_item__student_id'
def student_item_id(self, obj):
url = reverse(
'admin:submissions_studentitem_change',
args=[obj.student_item.id]
)
return u'<a href="{}">{}</a>'.format(url, obj.student_item.id)
student_item_id.allow_tags = True
student_item_id.admin_order_field = 'student_item__id'
student_item_id.short_description = 'S.I. ID'
class StudentItemAdmin(admin.ModelAdmin):
list_display = ('id', 'course_id', 'item_type', 'item_id', 'student_id')
list_filter = ('item_type',)
search_fields = ('id', 'course_id', 'item_type', 'item_id', 'student_id')
readonly_fields = ('course_id', 'item_type', 'item_id', 'student_id')
class SubmissionAdmin(admin.ModelAdmin, StudentItemAdminMixin):
list_display = (
'id', 'uuid',
'course_id', 'item_id', 'student_id', 'student_item_id',
'attempt_number', 'submitted_at',
)
list_display_links = ('id', 'uuid')
list_filter = ('student_item__item_type',)
readonly_fields = (
'student_item_id',
'course_id', 'item_id', 'student_id',
'attempt_number', 'submitted_at', 'created_at',
'raw_answer', 'all_scores',
)
search_fields = ('id', 'uuid') + StudentItemAdminMixin.search_fields
# We're creating our own explicit link and displaying parts of the
# student_item in separate fields -- no need to display this as well.
exclude = ('student_item',)
def all_scores(self, submission):
return "\n".join(
"{}/{} - {}".format(
score.points_earned, score.points_possible, score.created_at
)
for score in Score.objects.filter(submission=submission)
)
class ScoreAdmin(admin.ModelAdmin, StudentItemAdminMixin):
list_display = (
'id',
'course_id', 'item_id', 'student_id', 'student_item_id',
'points', 'created_at'
)
list_filter = ('student_item__item_type',)
readonly_fields = (
'student_item_id',
'student_item',
'submission',
'points_earned',
'points_possible',
'reset',
)
search_fields = ('id', ) + StudentItemAdminMixin.search_fields
def points(self, score):
return u"{}/{}".format(score.points_earned, score.points_possible)
class ScoreSummaryAdmin(admin.ModelAdmin, StudentItemAdminMixin):
list_display = (
'id',
'course_id', 'item_id', 'student_id', 'student_item_id',
'latest', 'highest',
)
search_fields = ('id', ) + StudentItemAdminMixin.search_fields
readonly_fields = (
'student_item_id', 'student_item', 'highest_link', 'latest_link'
)
exclude = ('highest', 'latest')
def highest_link(self, score_summary):
url = reverse(
'admin:submissions_score_change', args=[score_summary.highest.id]
)
return u'<a href="{}">{}</a>'.format(url, score_summary.highest)
highest_link.allow_tags = True
highest_link.short_description = 'Highest'
def latest_link(self, score_summary):
url = reverse(
'admin:submissions_score_change', args=[score_summary.latest.id]
)
return u'<a href="{}">{}</a>'.format(url, score_summary.latest)
latest_link.allow_tags = True
latest_link.short_description = 'Latest'
admin.site.register(Score, ScoreAdmin)
admin.site.register(StudentItem, StudentItemAdmin)
admin.site.register(Submission, SubmissionAdmin)
admin.site.register(ScoreSummary, ScoreSummaryAdmin)
\ No newline at end of file
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'StudentItem'
db.create_table('submissions_studentitem', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('student_id', self.gf('django.db.models.fields.CharField')(max_length=255, db_index=True)),
('course_id', self.gf('django.db.models.fields.CharField')(max_length=255, db_index=True)),
('item_id', self.gf('django.db.models.fields.CharField')(max_length=255, db_index=True)),
('item_type', self.gf('django.db.models.fields.CharField')(max_length=100)),
))
db.send_create_signal('submissions', ['StudentItem'])
# Adding unique constraint on 'StudentItem', fields ['course_id', 'student_id', 'item_id']
db.create_unique('submissions_studentitem', ['course_id', 'student_id', 'item_id'])
# Adding model 'Submission'
db.create_table('submissions_submission', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('uuid', self.gf('django.db.models.fields.CharField')(db_index=True, max_length=36, blank=True)),
('student_item', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['submissions.StudentItem'])),
('attempt_number', self.gf('django.db.models.fields.PositiveIntegerField')()),
('submitted_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, db_index=True)),
('created_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, db_index=True)),
('answer', self.gf('django.db.models.fields.TextField')(blank=True)),
))
db.send_create_signal('submissions', ['Submission'])
# Adding model 'Score'
db.create_table('submissions_score', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('student_item', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['submissions.StudentItem'])),
('submission', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['submissions.Submission'], null=True)),
('points_earned', self.gf('django.db.models.fields.PositiveIntegerField')(default=0)),
('points_possible', self.gf('django.db.models.fields.PositiveIntegerField')(default=0)),
('created_at', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now, db_index=True)),
))
db.send_create_signal('submissions', ['Score'])
def backwards(self, orm):
# Removing unique constraint on 'StudentItem', fields ['course_id', 'student_id', 'item_id']
db.delete_unique('submissions_studentitem', ['course_id', 'student_id', 'item_id'])
# Deleting model 'StudentItem'
db.delete_table('submissions_studentitem')
# Deleting model 'Submission'
db.delete_table('submissions_submission')
# Deleting model 'Score'
db.delete_table('submissions_score')
models = {
'submissions.score': {
'Meta': {'object_name': 'Score'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'points_earned': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'points_possible': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']"}),
'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.Submission']", 'null': 'True'})
},
'submissions.studentitem': {
'Meta': {'unique_together': "(('course_id', 'student_id', 'item_id'),)", 'object_name': 'StudentItem'},
'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'item_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'item_type': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'student_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})
},
'submissions.submission': {
'Meta': {'ordering': "['-submitted_at', '-id']", 'object_name': 'Submission'},
'answer': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'attempt_number': ('django.db.models.fields.PositiveIntegerField', [], {}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']"}),
'submitted_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'uuid': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '36', 'blank': 'True'})
}
}
complete_apps = ['submissions']
\ No newline at end of file
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ScoreSummary'
db.create_table('submissions_scoresummary', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('student_item', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['submissions.StudentItem'], unique=True)),
('highest', self.gf('django.db.models.fields.related.ForeignKey')(related_name='+', to=orm['submissions.Score'])),
('latest', self.gf('django.db.models.fields.related.ForeignKey')(related_name='+', to=orm['submissions.Score'])),
))
db.send_create_signal('submissions', ['ScoreSummary'])
def backwards(self, orm):
# Deleting model 'ScoreSummary'
db.delete_table('submissions_scoresummary')
models = {
'submissions.score': {
'Meta': {'object_name': 'Score'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'points_earned': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'points_possible': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']"}),
'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.Submission']", 'null': 'True'})
},
'submissions.scoresummary': {
'Meta': {'object_name': 'ScoreSummary'},
'highest': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'+'", 'to': "orm['submissions.Score']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'latest': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'+'", 'to': "orm['submissions.Score']"}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']", 'unique': 'True'})
},
'submissions.studentitem': {
'Meta': {'unique_together': "(('course_id', 'student_id', 'item_id'),)", 'object_name': 'StudentItem'},
'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'item_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'item_type': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'student_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})
},
'submissions.submission': {
'Meta': {'ordering': "['-submitted_at', '-id']", 'object_name': 'Submission'},
'answer': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'attempt_number': ('django.db.models.fields.PositiveIntegerField', [], {}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']"}),
'submitted_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'uuid': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '36', 'blank': 'True'})
}
}
complete_apps = ['submissions']
\ No newline at end of file
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Submission.answer'
db.delete_column('submissions_submission', 'answer')
# Adding field 'Submission.raw_answer'
db.add_column('submissions_submission', 'raw_answer',
self.gf('django.db.models.fields.TextField')(default='', blank=True),
keep_default=False)
def backwards(self, orm):
# Adding field 'Submission.answer'
db.add_column('submissions_submission', 'answer',
self.gf('django.db.models.fields.TextField')(default='', blank=True),
keep_default=False)
# Deleting field 'Submission.raw_answer'
db.delete_column('submissions_submission', 'raw_answer')
models = {
'submissions.score': {
'Meta': {'object_name': 'Score'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'points_earned': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'points_possible': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']"}),
'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.Submission']", 'null': 'True'})
},
'submissions.scoresummary': {
'Meta': {'object_name': 'ScoreSummary'},
'highest': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'+'", 'to': "orm['submissions.Score']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'latest': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'+'", 'to': "orm['submissions.Score']"}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']", 'unique': 'True'})
},
'submissions.studentitem': {
'Meta': {'unique_together': "(('course_id', 'student_id', 'item_id'),)", 'object_name': 'StudentItem'},
'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'item_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'item_type': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'student_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})
},
'submissions.submission': {
'Meta': {'ordering': "['-submitted_at', '-id']", 'object_name': 'Submission'},
'attempt_number': ('django.db.models.fields.PositiveIntegerField', [], {}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'raw_answer': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']"}),
'submitted_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'uuid': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '36', 'blank': 'True'})
}
}
complete_apps = ['submissions']
\ No newline at end of file
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Score.reset'
db.add_column('submissions_score', 'reset',
self.gf('django.db.models.fields.BooleanField')(default=False),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Score.reset'
db.delete_column('submissions_score', 'reset')
models = {
'submissions.score': {
'Meta': {'object_name': 'Score'},
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'points_earned': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'points_possible': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'reset': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']"}),
'submission': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.Submission']", 'null': 'True'})
},
'submissions.scoresummary': {
'Meta': {'object_name': 'ScoreSummary'},
'highest': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'+'", 'to': "orm['submissions.Score']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'latest': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'+'", 'to': "orm['submissions.Score']"}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']", 'unique': 'True'})
},
'submissions.studentitem': {
'Meta': {'unique_together': "(('course_id', 'student_id', 'item_id'),)", 'object_name': 'StudentItem'},
'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'item_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'item_type': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'student_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'})
},
'submissions.submission': {
'Meta': {'ordering': "['-submitted_at', '-id']", 'object_name': 'Submission'},
'attempt_number': ('django.db.models.fields.PositiveIntegerField', [], {}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'raw_answer': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'student_item': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['submissions.StudentItem']"}),
'submitted_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'uuid': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '36', 'blank': 'True'})
}
}
complete_apps = ['submissions']
\ No newline at end of file
"""
Submission models hold student responses to problems, scores, and a history of
those scores. It is intended to be a general purpose store that is usable by
different problem types, and is therefore ignorant of ORA workflow.
NOTE: We've switched to migrations, so if you make any edits to this file, you
need to then generate a matching migration for it using:
./manage.py schemamigration submissions --auto
"""
import json
import logging
from django.db import models, DatabaseError
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.timezone import now
from django_extensions.db.fields import UUIDField
logger = logging.getLogger(__name__)
class StudentItem(models.Model):
"""Represents a single item for a single course for a single user.
This is typically an XBlock problem, but could be something more generic
like class participation.
"""
# The anonymized Student ID that the XBlock sees, not their real ID.
student_id = models.CharField(max_length=255, blank=False, db_index=True)
# Not sure yet whether these are legacy course_ids or new course_ids
course_id = models.CharField(max_length=255, blank=False, db_index=True)
# Version independent, course-local content identifier, i.e. the problem
# This is the block_id for XBlock items.
item_id = models.CharField(max_length=255, blank=False, db_index=True)
# What kind of problem is this? The XBlock tag if it's an XBlock
item_type = models.CharField(max_length=100)
def __repr__(self):
return repr(dict(
student_id=self.student_id,
course_id=self.course_id,
item_id=self.item_id,
item_type=self.item_type,
))
def __unicode__(self):
return u"({0.student_id}, {0.course_id}, {0.item_type}, {0.item_id})".format(self)
class Meta:
unique_together = (
# For integrity reasons, and looking up all of a student's items
("course_id", "student_id", "item_id"),
)
class Submission(models.Model):
"""A single response by a student for a given problem in a given course.
A student may have multiple submissions for the same problem. Submissions
should never be mutated. If the student makes another Submission, or if we
have to make corrective Submissions to fix bugs, those should be new
objects. We want to keep Submissions immutable both for audit purposes, and
because it makes caching trivial.
"""
MAXSIZE = 1024*100 # 100KB
uuid = UUIDField(version=1, db_index=True)
student_item = models.ForeignKey(StudentItem)
# Which attempt is this? Consecutive Submissions do not necessarily have
# increasing attempt_number entries -- e.g. re-scoring a buggy problem.
attempt_number = models.PositiveIntegerField()
# submitted_at is separate from created_at to support re-scoring and other
# processes that might create Submission objects for past user actions.
submitted_at = models.DateTimeField(default=now, db_index=True)
# When this row was created.
created_at = models.DateTimeField(editable=False, default=now, db_index=True)
# The answer (JSON-serialized)
raw_answer = models.TextField(blank=True)
def __repr__(self):
return repr(dict(
uuid=self.uuid,
student_item=self.student_item,
attempt_number=self.attempt_number,
submitted_at=self.submitted_at,
created_at=self.created_at,
raw_answer=self.raw_answer,
))
def __unicode__(self):
return u"Submission {}".format(self.uuid)
class Meta:
ordering = ["-submitted_at", "-id"]
class Score(models.Model):
"""What the user scored for a given StudentItem at a given time.
Note that while a Score *can* be tied to a Submission, it doesn't *have* to.
Specifically, if we want to have scores for things that are not a part of
the courseware (like "class participation"), there would be no corresponding
Submission.
"""
student_item = models.ForeignKey(StudentItem)
submission = models.ForeignKey(Submission, null=True)
points_earned = models.PositiveIntegerField(default=0)
points_possible = models.PositiveIntegerField(default=0)
created_at = models.DateTimeField(editable=False, default=now, db_index=True)
# Flag to indicate that this score should reset the current "highest" score
reset = models.BooleanField(default=False)
@property
def submission_uuid(self):
"""
Retrieve the submission UUID associated with this score.
If the score isn't associated with a submission (for example, if this is
a "reset" score or a a non-courseware item like "class participation"),
then this will return None.
Returns:
str or None
"""
if self.submission is not None:
return self.submission.uuid
else:
return None
def to_float(self):
"""
Calculate (points earned) / (points possible).
If points possible is None (e.g. this is a "hidden" score)
then return None.
Returns:
float or None
"""
if self.points_possible == 0:
return None
return float(self.points_earned) / self.points_possible
def __repr__(self):
return repr(dict(
student_item=self.student_item,
submission=self.submission,
created_at=self.created_at,
points_earned=self.points_earned,
points_possible=self.points_possible,
))
def is_hidden(self):
"""
By convention, a score of 0/0 is not displayed to users.
Hidden scores are filtered by the submissions API.
Returns:
bool: Whether the score should be hidden.
"""
return self.points_possible == 0
@classmethod
def create_reset_score(cls, student_item):
"""
Create a "reset" score (a score with a null submission).
Only scores created after the most recent "reset" score
should be used to determine a student's effective score.
Args:
student_item (StudentItem): The student item model.
Returns:
Score: The newly created "reset" score.
Raises:
DatabaseError: An error occurred while creating the score
"""
# By setting the "reset" flag, we ensure that the "highest"
# score in the score summary will point to this score.
# By setting points earned and points possible to 0,
# we ensure that this score will be hidden from the user.
return cls.objects.create(
student_item=student_item,
submission=None,
points_earned=0,
points_possible=0,
reset=True,
)
def __unicode__(self):
return u"{0.points_earned}/{0.points_possible}".format(self)
class ScoreSummary(models.Model):
"""Running store of the highest and most recent Scores for a StudentItem."""
student_item = models.ForeignKey(StudentItem, unique=True)
highest = models.ForeignKey(Score, related_name="+")
latest = models.ForeignKey(Score, related_name="+")
class Meta:
verbose_name_plural = "Score Summaries"
@receiver(post_save, sender=Score)
def update_score_summary(sender, **kwargs):
"""
Listen for new Scores and update the relevant ScoreSummary.
Args:
sender: not used
Kwargs:
instance (Score): The score model whose save triggered this receiver.
"""
score = kwargs['instance']
try:
score_summary = ScoreSummary.objects.get(
student_item=score.student_item
)
score_summary.latest = score
# A score with the "reset" flag set will always replace the current highest score
if score.reset:
score_summary.highest = score
# The conversion to a float may return None if points possible is zero
# In Python, None is always less than an integer, so any score
# with non-null points possible will take precedence.
elif score.to_float() > score_summary.highest.to_float():
score_summary.highest = score
score_summary.save()
except ScoreSummary.DoesNotExist:
ScoreSummary.objects.create(
student_item=score.student_item,
highest=score,
latest=score,
)
except DatabaseError as err:
logger.exception(
u"Error while updating score summary for student item {}"
.format(score.student_item)
)
"""
Serializers are created to ensure models do not have to be accessed outside the
scope of the Tim APIs.
"""
import json
from rest_framework import serializers
from submissions.models import StudentItem, Submission, Score
class JsonFieldError(Exception):
"""
An error occurred while serializing/deserializing JSON.
"""
pass
class JsonField(serializers.WritableField):
"""
JSON-serializable field.
"""
def to_native(self, obj):
"""
Deserialize the JSON string.
Args:
obj (str): The JSON string stored in the database.
Returns:
JSON-serializable
Raises:
JsonFieldError: The field could not be deserialized.
"""
try:
return json.loads(obj)
except (TypeError, ValueError):
raise JsonFieldError(u"Could not deserialize as JSON: {}".format(obj))
def from_native(self, data):
"""
Serialize an object to JSON.
Args:
data (JSON-serializable): The data to serialize.
Returns:
str
Raises:
ValueError: The data could not be serialized as JSON.
"""
try:
return json.dumps(data)
except (TypeError, ValueError):
raise JsonFieldError(u"Could not serialize as JSON: {}".format(data))
class StudentItemSerializer(serializers.ModelSerializer):
class Meta:
model = StudentItem
fields = ('student_id', 'course_id', 'item_id', 'item_type')
class SubmissionSerializer(serializers.ModelSerializer):
answer = JsonField(source='raw_answer')
def validate_answer(self, attrs, source):
"""Check that the answer is within an acceptable size range."""
value = attrs[source]
if len(value) > Submission.MAXSIZE:
raise serializers.ValidationError("Maximum answer size exceeded.")
return attrs
class Meta:
model = Submission
fields = (
'uuid',
'student_item',
'attempt_number',
'submitted_at',
'created_at',
# Computed
'answer',
)
class ScoreSerializer(serializers.ModelSerializer):
submission_uuid = serializers.Field(source='submission_uuid')
class Meta:
model = Score
fields = (
'student_item',
'submission',
'points_earned',
'points_possible',
'created_at',
# Computed
'submission_uuid',
)
<h3>Submissions for {{ student_id }} > {{ course_id }} > {{ item_id }}:</h3>
{{ error }} <br/>
{{ submissions|length }} total submissions. <br/>
<br/>
<table border=1>
<th>Submission UUID</th>
<th>Student Item</th>
<th>Attempt Number</th>
<th>Answer</th>
<th>Submitted At</th>
<th>Created At</th>
{% for submission in submissions%}
<tr>
<td>{{ submission.uuid }}</td>
<td>{{ submission.student_item }}</td>
<td>{{ submission.attempt_number }}</td>
<td>{{ submission.answer }}</td>
<td>{{ submission.submitted_at }}</td>
<td>{{ submission.created_at }}</td>
</tr>
{% endfor %}
</table>
{
"no_item_type": {
"student_id": "Bad Tim",
"course_id": "451",
"item_id": "2"
},
"no_student_id": {
"course_id": "Course_One",
"item_id": "5",
"item_type": "Peer"
},
"just_student_and_course": {
"student_id": "Tim",
"course_id": "Course_One"
},
"just_student_id": {
"student_id": "Tim"
},
"just_item_id_and_type": {
"item_id": "5",
"item_type": "Peer"
},
"just_course_id": {
"course_id": "Course_One"
},
"just_item_id": {
"item_id": "5"
},
"bad_item_id_empty": {
"student_id": "Tim",
"course_id": "Course_One",
"item_id": "",
"item_type": "Peer"
}
}
\ No newline at end of file
{
"unicode_characters": {
"student_id": "学生",
"course_id": "漢字",
"item_id": "这是中国",
"item_type": "窥视"
},
"basic_student_item": {
"student_id": "Tom",
"course_id": "Demo_Course",
"item_id": "1",
"item_type": "Peer"
}
}
\ No newline at end of file
"""
Tests for submission models.
"""
from django.test import TestCase
from submissions.models import Submission, Score, ScoreSummary, StudentItem
class TestScoreSummary(TestCase):
"""
Test selection of options from a rubric.
"""
def test_latest(self):
item = StudentItem.objects.create(
student_id="score_test_student",
course_id="score_test_course",
item_id="i4x://mycourse/class_participation.section_attendance"
)
first_score = Score.objects.create(
student_item=item,
submission=None,
points_earned=8,
points_possible=10,
)
second_score = Score.objects.create(
student_item=item,
submission=None,
points_earned=5,
points_possible=10,
)
latest_score = ScoreSummary.objects.get(student_item=item).latest
self.assertEqual(second_score, latest_score)
def test_highest(self):
item = StudentItem.objects.create(
student_id="score_test_student",
course_id="score_test_course",
item_id="i4x://mycourse/special_presentation"
)
# Low score is higher than no score...
low_score = Score.objects.create(
student_item=item,
points_earned=0,
points_possible=0,
)
self.assertEqual(
low_score,
ScoreSummary.objects.get(student_item=item).highest
)
# Medium score should supplant low score
med_score = Score.objects.create(
student_item=item,
points_earned=8,
points_possible=10,
)
self.assertEqual(
med_score,
ScoreSummary.objects.get(student_item=item).highest
)
# Even though the points_earned is higher in the med_score, high_score
# should win because it's 4/4 as opposed to 8/10.
high_score = Score.objects.create(
student_item=item,
points_earned=4,
points_possible=4,
)
self.assertEqual(
high_score,
ScoreSummary.objects.get(student_item=item).highest
)
# Put another medium score to make sure it doesn't get set back down
med_score2 = Score.objects.create(
student_item=item,
points_earned=5,
points_possible=10,
)
self.assertEqual(
high_score,
ScoreSummary.objects.get(student_item=item).highest
)
self.assertEqual(
med_score2,
ScoreSummary.objects.get(student_item=item).latest
)
def test_reset_score_highest(self):
item = StudentItem.objects.create(
student_id="score_test_student",
course_id="score_test_course",
item_id="i4x://mycourse/special_presentation"
)
# Reset score with no score
Score.create_reset_score(item)
highest = ScoreSummary.objects.get(student_item=item).highest
self.assertEqual(highest.points_earned, 0)
self.assertEqual(highest.points_possible, 0)
# Non-reset score after a reset score
submission = Submission.objects.create(student_item=item, attempt_number=1)
Score.objects.create(
student_item=item,
submission=submission,
points_earned=2,
points_possible=3,
)
highest = ScoreSummary.objects.get(student_item=item).highest
self.assertEqual(highest.points_earned, 2)
self.assertEqual(highest.points_possible, 3)
# Reset score after a non-reset score
Score.create_reset_score(item)
highest = ScoreSummary.objects.get(student_item=item).highest
self.assertEqual(highest.points_earned, 0)
self.assertEqual(highest.points_possible, 0)
def test_highest_score_hidden(self):
item = StudentItem.objects.create(
student_id="score_test_student",
course_id="score_test_course",
item_id="i4x://mycourse/special_presentation"
)
# Score with points possible set to 0
# (by convention a "hidden" score)
submission = Submission.objects.create(student_item=item, attempt_number=1)
Score.objects.create(
student_item=item,
submission=submission,
points_earned=0,
points_possible=0,
)
highest = ScoreSummary.objects.get(student_item=item).highest
self.assertEqual(highest.points_earned, 0)
self.assertEqual(highest.points_possible, 0)
# Score with points
submission = Submission.objects.create(student_item=item, attempt_number=1)
Score.objects.create(
student_item=item,
submission=submission,
points_earned=1,
points_possible=2,
)
highest = ScoreSummary.objects.get(student_item=item).highest
self.assertEqual(highest.points_earned, 1)
self.assertEqual(highest.points_possible, 2)
# Another score with points possible set to 0
# The previous score should remain the highest score.
submission = Submission.objects.create(student_item=item, attempt_number=1)
Score.objects.create(
student_item=item,
submission=submission,
points_earned=0,
points_possible=0,
)
highest = ScoreSummary.objects.get(student_item=item).highest
self.assertEqual(highest.points_earned, 1)
self.assertEqual(highest.points_possible, 2)
"""
Test reset scores.
"""
import copy
from mock import patch
from django.test import TestCase
import ddt
from django.core.cache import cache
from django.db import DatabaseError
from submissions import api as sub_api
from submissions.models import Score
@ddt.ddt
class TestResetScore(TestCase):
"""
Test resetting scores for a specific student on a specific problem.
"""
STUDENT_ITEM = {
'student_id': 'Test student',
'course_id': 'Test course',
'item_id': 'Test item',
'item_type': 'Test item type',
}
def setUp(self):
"""
Clear the cache.
"""
cache.clear()
def test_reset_with_no_scores(self):
sub_api.reset_score(
self.STUDENT_ITEM['student_id'],
self.STUDENT_ITEM['course_id'],
self.STUDENT_ITEM['item_id'],
)
self.assertIs(sub_api.get_score(self.STUDENT_ITEM), None)
scores = sub_api.get_scores(self.STUDENT_ITEM['course_id'], self.STUDENT_ITEM['student_id'])
self.assertEqual(len(scores), 0)
def test_reset_with_one_score(self):
# Create a submission for the student and score it
submission = sub_api.create_submission(self.STUDENT_ITEM, 'test answer')
sub_api.set_score(submission['uuid'], 1, 2)
# Reset scores
sub_api.reset_score(
self.STUDENT_ITEM['student_id'],
self.STUDENT_ITEM['course_id'],
self.STUDENT_ITEM['item_id'],
)
# Expect that no scores are available for the student
self.assertIs(sub_api.get_score(self.STUDENT_ITEM), None)
scores = sub_api.get_scores(self.STUDENT_ITEM['course_id'], self.STUDENT_ITEM['student_id'])
self.assertEqual(len(scores), 0)
def test_reset_with_multiple_scores(self):
# Create a submission for the student and score it
submission = sub_api.create_submission(self.STUDENT_ITEM, 'test answer')
sub_api.set_score(submission['uuid'], 1, 2)
sub_api.set_score(submission['uuid'], 2, 2)
# Reset scores
sub_api.reset_score(
self.STUDENT_ITEM['student_id'],
self.STUDENT_ITEM['course_id'],
self.STUDENT_ITEM['item_id'],
)
# Expect that no scores are available for the student
self.assertIs(sub_api.get_score(self.STUDENT_ITEM), None)
scores = sub_api.get_scores(self.STUDENT_ITEM['course_id'], self.STUDENT_ITEM['student_id'])
self.assertEqual(len(scores), 0)
@ddt.data(
{'student_id': 'other student'},
{'course_id': 'other course'},
{'item_id': 'other item'},
)
def test_reset_different_student_item(self, changed):
# Create a submissions for two students
submission = sub_api.create_submission(self.STUDENT_ITEM, 'test answer')
sub_api.set_score(submission['uuid'], 1, 2)
other_student = copy.copy(self.STUDENT_ITEM)
other_student.update(changed)
submission = sub_api.create_submission(other_student, 'other test answer')
sub_api.set_score(submission['uuid'], 3, 4)
# Reset the score for the first student
sub_api.reset_score(
self.STUDENT_ITEM['student_id'],
self.STUDENT_ITEM['course_id'],
self.STUDENT_ITEM['item_id'],
)
# The first student's scores should be reset
self.assertIs(sub_api.get_score(self.STUDENT_ITEM), None)
scores = sub_api.get_scores(self.STUDENT_ITEM['course_id'], self.STUDENT_ITEM['student_id'])
self.assertNotIn(self.STUDENT_ITEM['item_id'], scores)
# But the second student should still have a score
score = sub_api.get_score(other_student)
self.assertEqual(score['points_earned'], 3)
self.assertEqual(score['points_possible'], 4)
scores = sub_api.get_scores(other_student['course_id'], other_student['student_id'])
self.assertIn(other_student['item_id'], scores)
def test_reset_then_add_score(self):
# Create a submission for the student and score it
submission = sub_api.create_submission(self.STUDENT_ITEM, 'test answer')
sub_api.set_score(submission['uuid'], 1, 2)
# Reset scores
sub_api.reset_score(
self.STUDENT_ITEM['student_id'],
self.STUDENT_ITEM['course_id'],
self.STUDENT_ITEM['item_id'],
)
# Score the student again
sub_api.set_score(submission['uuid'], 3, 4)
# Expect that the new score is available
score = sub_api.get_score(self.STUDENT_ITEM)
self.assertEqual(score['points_earned'], 3)
self.assertEqual(score['points_possible'], 4)
scores = sub_api.get_scores(self.STUDENT_ITEM['course_id'], self.STUDENT_ITEM['student_id'])
self.assertIn(self.STUDENT_ITEM['item_id'], scores)
self.assertEqual(scores[self.STUDENT_ITEM['item_id']], (3, 4))
def test_reset_then_get_score_for_submission(self):
# Create a submission for the student and score it
submission = sub_api.create_submission(self.STUDENT_ITEM, 'test answer')
sub_api.set_score(submission['uuid'], 1, 2)
# Reset scores
sub_api.reset_score(
self.STUDENT_ITEM['student_id'],
self.STUDENT_ITEM['course_id'],
self.STUDENT_ITEM['item_id'],
)
# If we're retrieving the score for a particular submission,
# instead of a student item, then we should STILL get a score.
self.assertIsNot(sub_api.get_latest_score_for_submission(submission['uuid']), None)
@patch.object(Score.objects, 'create')
def test_database_error(self, create_mock):
# Create a submission for the student and score it
submission = sub_api.create_submission(self.STUDENT_ITEM, 'test answer')
sub_api.set_score(submission['uuid'], 1, 2)
# Simulate a database error when creating the reset score
create_mock.side_effect = DatabaseError("Test error")
with self.assertRaises(sub_api.SubmissionInternalError):
sub_api.reset_score(
self.STUDENT_ITEM['student_id'],
self.STUDENT_ITEM['course_id'],
self.STUDENT_ITEM['item_id'],
)
"""
Tests for submissions serializers.
"""
from django.test import TestCase
from submissions.models import Score, StudentItem
from submissions.serializers import ScoreSerializer
class ScoreSerializerTest(TestCase):
"""
Tests for the score serializer.
"""
def test_score_with_null_submission(self):
item = StudentItem.objects.create(
student_id="score_test_student",
course_id="score_test_course",
item_id="i4x://mycourse/special_presentation"
)
# Create a score with a null submission
score = Score.objects.create(
student_item=item,
submission=None,
points_earned=2,
points_possible=6
)
score_dict = ScoreSerializer(score).data
self.assertIs(score_dict['submission_uuid'], None)
self.assertEqual(score_dict['points_earned'], 2)
self.assertEqual(score_dict['points_possible'], 6)
from django.conf.urls import patterns, url
urlpatterns = patterns(
'submissions.views',
url(
r'^(?P<student_id>[^/]+)/(?P<course_id>[^/]+)/(?P<item_id>[^/]+)$',
'get_submissions_for_student_item'
),
)
import logging
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from submissions.api import SubmissionRequestError, get_submissions
log = logging.getLogger(__name__)
@login_required()
def get_submissions_for_student_item(request, course_id, student_id, item_id):
"""Retrieve all submissions associated with the given student item.
Developer utility for accessing all the submissions associated with a
student item. The student item is specified by the unique combination of
course, student, and item.
Args:
request (dict): The request.
course_id (str): The course id for this student item.
student_id (str): The student id for this student item.
item_id (str): The item id for this student item.
Returns:
HttpResponse: The response object for this request. Renders a simple
development page with all the submissions related to the specified
student item.
"""
student_item_dict = dict(
course_id=course_id,
student_id=student_id,
item_id=item_id,
)
context = dict(**student_item_dict)
try:
submissions = get_submissions(student_item_dict)
context["submissions"] = submissions
except SubmissionRequestError:
context["error"] = "The specified student item was not found."
return render_to_response('submissions.html', context)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment