f4ad1b0ebbf9b28ab74d65bee211f3860464e233
[edumed.git] / wtem / admin.py
1 # -*- coding: utf-8 -*-
2
3 import os
4
5 from django.contrib import admin
6 from django import forms
7 from django.utils import simplejson
8
9 from .models import Submission, Assignment
10
11
12 f = file(os.path.dirname(__file__) + '/fixtures/exercises.json')
13 exercises = simplejson.loads(f.read())
14 f.close()
15
16 def get_user_exercises(user):
17     assignment = Assignment.objects.get(user = user)
18     return [e for e in exercises if e['id'] in assignment.exercises]
19
20
21 readonly_fields = ('contact', 'first_name', 'last_name', 'email', 'key', 'key_sent')
22
23
24 class SubmissionFormBase(forms.ModelForm):
25     class Meta:
26         model = Submission
27         exclude = ('answers', 'marks') + readonly_fields
28
29
30 def get_form(request, submission):
31     fields = dict()
32     if submission.answers:
33         answers = simplejson.loads(submission.answers)
34         user_exercises = get_user_exercises(request.user)
35         for exercise in exercises:
36             if exercise not in user_exercises:
37                 continue
38             if exercise['type'] == 'open':
39                 answer_field_name = 'exercise_%s' % exercise['id']
40                 mark_field_name = 'markof_%s_by_%s' % (exercise['id'], request.user.id)
41                 fields[answer_field_name] = forms.CharField(
42                     widget = forms.Textarea(attrs={'readonly':True}),
43                     initial = answers[str(exercise['id'])],
44                     label = 'Rozwiązanie zadania %s' % exercise['id']
45                 )
46
47                 fields[mark_field_name] = forms.ChoiceField(
48                     choices = [(None, '-')] + [(i,i) for i in range(exercise['max_points']+1)],
49                     initial = submission.get_mark(user_id = request.user.id, exercise_id = exercise['id']),
50                     label = u'Twoja ocena zadania %s' % exercise['id']
51                 )
52     return type('SubmissionForm', (SubmissionFormBase,), fields)
53
54
55 class SubmissionAdmin(admin.ModelAdmin):
56     readonly_fields = readonly_fields
57
58     def get_form(self, request, obj, **kwargs):
59         return get_form(request, obj)
60     
61     def save_model(self, request, submission, form, change):
62         for name, value in form.cleaned_data.items():
63             if name.startswith('markof_'):
64                 parts = name.split('_')
65                 exercise_id = parts[1]
66                 user_id = parts[3]
67                 submission.set_mark(user_id = user_id, exercise_id = exercise_id, mark = value)
68         submission.save()
69
70
71 admin.site.register(Submission, SubmissionAdmin)
72 admin.site.register(Assignment)