From cc7808417c18e06b6d8c7b68f2b045632103fa08 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Aleksander=20=C5=81ukasz?= Date: Wed, 6 Nov 2013 12:38:41 +0100 Subject: [PATCH 1/1] Marking open questions via admin form --- wtem/admin.py | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 69 insertions(+), 1 deletion(-) diff --git a/wtem/admin.py b/wtem/admin.py index 0d7cd14..f4ad1b0 100644 --- a/wtem/admin.py +++ b/wtem/admin.py @@ -1,4 +1,72 @@ +# -*- coding: utf-8 -*- + +import os + from django.contrib import admin -from .models import Assignment +from django import forms +from django.utils import simplejson + +from .models import Submission, Assignment + + +f = file(os.path.dirname(__file__) + '/fixtures/exercises.json') +exercises = simplejson.loads(f.read()) +f.close() + +def get_user_exercises(user): + assignment = Assignment.objects.get(user = user) + return [e for e in exercises if e['id'] in assignment.exercises] + + +readonly_fields = ('contact', 'first_name', 'last_name', 'email', 'key', 'key_sent') + + +class SubmissionFormBase(forms.ModelForm): + class Meta: + model = Submission + exclude = ('answers', 'marks') + readonly_fields + + +def get_form(request, submission): + fields = dict() + if submission.answers: + answers = simplejson.loads(submission.answers) + user_exercises = get_user_exercises(request.user) + for exercise in exercises: + if exercise not in user_exercises: + continue + if exercise['type'] == 'open': + answer_field_name = 'exercise_%s' % exercise['id'] + mark_field_name = 'markof_%s_by_%s' % (exercise['id'], request.user.id) + fields[answer_field_name] = forms.CharField( + widget = forms.Textarea(attrs={'readonly':True}), + initial = answers[str(exercise['id'])], + label = 'Rozwiązanie zadania %s' % exercise['id'] + ) + + fields[mark_field_name] = forms.ChoiceField( + choices = [(None, '-')] + [(i,i) for i in range(exercise['max_points']+1)], + initial = submission.get_mark(user_id = request.user.id, exercise_id = exercise['id']), + label = u'Twoja ocena zadania %s' % exercise['id'] + ) + return type('SubmissionForm', (SubmissionFormBase,), fields) + + +class SubmissionAdmin(admin.ModelAdmin): + readonly_fields = readonly_fields + + def get_form(self, request, obj, **kwargs): + return get_form(request, obj) + + def save_model(self, request, submission, form, change): + for name, value in form.cleaned_data.items(): + if name.startswith('markof_'): + parts = name.split('_') + exercise_id = parts[1] + user_id = parts[3] + submission.set_mark(user_id = user_id, exercise_id = exercise_id, mark = value) + submission.save() + +admin.site.register(Submission, SubmissionAdmin) admin.site.register(Assignment) \ No newline at end of file -- 2.20.1