new question
[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         if isinstance(answer, list):
42             toret = ''
43             for part in answer:
44                 field = get_option(exercise['fields'], part['id'])
45                 toret += '- %s:\n\n%s\n\n' % (field['caption'], part['text'])
46         else:
47             toret = answer
48     if exercise['type'] == 'edumed_wybor':
49         ok = set(map(str, exercise['answer'])) == set(map(str,answer['closed_part']))
50         toret = u'Czesc testowa [%s]:\n' % ('poprawna' if ok else 'niepoprawna')
51         for selected in answer['closed_part']:
52             option = get_option(exercise['options'], selected)
53             toret += '%s: %s\n' % (selected, option['text'])
54         else:
55             toret += u'<nie wybrano odpowiedzi>\n'
56         toret += u'\nCzesc otwarta (%s):\n\n' % ' '.join(exercise['open_part'])
57         toret += answer['open_part']
58
59     return toret
60
61
62 def get_form(request, submission):
63     fields = dict()
64     if submission.answers:
65         answers = simplejson.loads(submission.answers)
66         user_exercises = get_user_exercises(request.user)
67         for exercise in exercises:
68             if exercise not in user_exercises:
69                 continue
70             if exercise['type'] == 'open' or exercise.get('open_part', None):
71                 answer_field_name = 'exercise_%s' % exercise['id']
72                 mark_field_name = 'markof_%s_by_%s' % (exercise['id'], request.user.id)
73                 fields[answer_field_name] = forms.CharField(
74                     widget = forms.Textarea(attrs={'readonly':True}),
75                     initial = get_open_answer(answers, exercise),
76                     label = 'Rozwiązanie zadania %s' % exercise['id']
77                 )
78
79                 fields[mark_field_name] = forms.ChoiceField(
80                     choices = [(None, '-')] + [(i,i) for i in range(exercise['max_points']+1)],
81                     initial = submission.get_mark(user_id = request.user.id, exercise_id = exercise['id']),
82                     label = u'Twoja ocena zadania %s' % exercise['id']
83                 )
84     return type('SubmissionForm', (SubmissionFormBase,), fields)
85
86
87 class SubmissionAdmin(admin.ModelAdmin):
88     list_display = ('__unicode__', 'todo',)
89     readonly_fields = readonly_fields
90
91     def get_form(self, request, obj, **kwargs):
92         return get_form(request, obj)
93     
94     def submitted_by(self, instance):
95         if instance.contact:
96             return '<a href="%s">%s</a>' % (
97                 reverse('admin:contact_contact_change', args = [instance.contact.id]),
98                 instance.contact.contact
99             )
100         return '-'
101     submitted_by.allow_tags = True
102     submitted_by.short_description = "Zgłoszony/a przez"
103
104     def todo(self, submission):
105         user = get_current_request().user
106         user_exercises = get_user_exercises(user)
107         user_marks = submission.marks.get(str(user.id), {})
108         return ','.join([str(e['id']) for e in user_exercises if str(e['id']) not in user_marks.keys()])
109
110     def save_model(self, request, submission, form, change):
111         for name, value in form.cleaned_data.items():
112             if name.startswith('markof_'):
113                 parts = name.split('_')
114                 exercise_id = parts[1]
115                 user_id = parts[3]
116                 submission.set_mark(user_id = user_id, exercise_id = exercise_id, mark = value)
117         submission.save()
118
119
120 admin.site.register(Submission, SubmissionAdmin)
121 admin.site.register(Assignment)