99877fd6e142854afd56c3be2884709d1c2cdca8
[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 from django.core.urlresolvers import reverse
9
10 from .models import Submission, Assignment
11 from .middleware import get_current_request
12
13
14 f = file(os.path.dirname(__file__) + '/fixtures/exercises.json')
15 exercises = simplejson.loads(f.read())
16 f.close()
17
18 def get_user_exercises(user):
19     assignment = Assignment.objects.get(user = user)
20     return [e for e in exercises if e['id'] in assignment.exercises]
21
22
23 readonly_fields = ('submitted_by', 'first_name', 'last_name', 'email', 'key', 'key_sent')
24
25
26 class SubmissionFormBase(forms.ModelForm):
27     class Meta:
28         model = Submission
29         exclude = ('answers', 'marks', 'contact') + readonly_fields
30
31
32 def get_open_answer(answers, exercise):
33     def get_option(options, id):
34         for option in options:
35             if option['id'] == int(id):
36                 return option
37
38     exercise_id = str(exercise['id'])
39     answer = answers[exercise_id]
40     if exercise['type'] == 'open':
41         toret = answer
42     if exercise['type'] == 'edumed_wybor':
43         ok = set(map(str, exercise['answer'])) == set(map(str,answer['closed_part']))
44         toret = u'Czesc testowa [%s]:\n' % ('poprawna' if ok else 'niepoprawna')
45         for selected in answer['closed_part']:
46             option = get_option(exercise['options'], selected)
47             toret += '%s: %s\n' % (selected, option['text'])
48         toret += u'\nCzesc otwarta (%s):\n\n' % ' '.join(exercise['open_part'])
49         toret += answer['open_part']
50
51     return toret
52
53
54 def get_form(request, submission):
55     fields = dict()
56     if submission.answers:
57         answers = simplejson.loads(submission.answers)
58         user_exercises = get_user_exercises(request.user)
59         for exercise in exercises:
60             if exercise not in user_exercises:
61                 continue
62             if exercise['type'] == 'open' or exercise.get('open_part', None):
63                 answer_field_name = 'exercise_%s' % exercise['id']
64                 mark_field_name = 'markof_%s_by_%s' % (exercise['id'], request.user.id)
65                 fields[answer_field_name] = forms.CharField(
66                     widget = forms.Textarea(attrs={'readonly':True}),
67                     initial = get_open_answer(answers, exercise),
68                     label = 'Rozwiązanie zadania %s' % exercise['id']
69                 )
70
71                 fields[mark_field_name] = forms.ChoiceField(
72                     choices = [(None, '-')] + [(i,i) for i in range(exercise['max_points']+1)],
73                     initial = submission.get_mark(user_id = request.user.id, exercise_id = exercise['id']),
74                     label = u'Twoja ocena zadania %s' % exercise['id']
75                 )
76     return type('SubmissionForm', (SubmissionFormBase,), fields)
77
78
79 class SubmissionAdmin(admin.ModelAdmin):
80     list_display = ('__unicode__', 'todo',)
81     readonly_fields = readonly_fields
82
83     def get_form(self, request, obj, **kwargs):
84         return get_form(request, obj)
85     
86     def submitted_by(self, instance):
87         if instance.contact:
88             return '<a href="%s">%s</a>' % (
89                 reverse('admin:contact_contact_change', args = [instance.contact.id]),
90                 instance.contact.contact
91             )
92         return '-'
93     submitted_by.allow_tags = True
94     submitted_by.short_description = "Zgłoszony/a przez"
95
96     def todo(self, submission):
97         user = get_current_request().user
98         user_exercises = get_user_exercises(user)
99         user_marks = submission.marks.get(str(user.id), {})
100         return ','.join([str(e['id']) for e in user_exercises if str(e['id']) not in user_marks.keys()])
101
102     def save_model(self, request, submission, form, change):
103         for name, value in form.cleaned_data.items():
104             if name.startswith('markof_'):
105                 parts = name.split('_')
106                 exercise_id = parts[1]
107                 user_id = parts[3]
108                 submission.set_mark(user_id = user_id, exercise_id = exercise_id, mark = value)
109         submission.save()
110
111
112 admin.site.register(Submission, SubmissionAdmin)
113 admin.site.register(Assignment)