47e0a77630c4e658a0102a2e4d11ea8efb17dfee
[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.utils.safestring import mark_safe
9 from django.core.urlresolvers import reverse
10
11 from .models import Submission, Assignment, Attachment, exercises
12 from .middleware import get_current_request
13
14
15 def get_user_exercises(user):
16     try:
17         assignment = Assignment.objects.get(user = user)
18         return [e for e in exercises if e['id'] in assignment.exercises]
19     except Assignment.DoesNotExist:
20         return []
21
22
23 readonly_fields = ('submitted_by', 'first_name', 'last_name', 'email', 'key', 'key_sent')
24
25 class AttachmentWidget(forms.Widget):
26     def render(self, name, value, *args, **kwargs):
27         return mark_safe('<input type="hidden" name="%s" value="%s"/><a href="%s">%s</a>' % (name, value, value, value))
28
29 class SubmissionFormBase(forms.ModelForm):
30     class Meta:
31         model = Submission
32         exclude = ('answers', 'marks', 'contact') + readonly_fields
33
34
35 def get_open_answer(answers, exercise):
36     def get_option(options, id):
37         for option in options:
38             if option['id'] == int(id):
39                 return option
40
41     exercise_id = str(exercise['id'])
42     answer = answers[exercise_id]
43     if exercise['type'] == 'open':
44         if isinstance(answer, list):
45             toret = ''
46             for part in answer:
47                 field = get_option(exercise['fields'], part['id'])
48                 toret += '- %s:\n\n%s\n\n' % (field['caption'], part['text'])
49         else:
50             toret = answer
51     if exercise['type'] == 'edumed_wybor':
52         ok = set(map(str, exercise['answer'])) == set(map(str,answer['closed_part']))
53         toret = u'Czesc testowa [%s]:\n' % ('poprawna' if ok else 'niepoprawna')
54         for selected in answer['closed_part']:
55             option = get_option(exercise['options'], selected)
56             toret += '%s: %s\n' % (selected, option['text'])
57         else:
58             toret += u'<nie wybrano odpowiedzi>\n'
59         toret += u'\nCzesc otwarta (%s):\n\n' % ' '.join(exercise['open_part'])
60         toret += answer['open_part']
61
62     return toret
63
64
65 def get_form(request, submission):
66     fields = dict()
67     if submission.answers:
68         answers = simplejson.loads(submission.answers)
69         user_exercises = get_user_exercises(request.user)
70         for exercise in exercises:
71             if exercise not in user_exercises:
72                 continue
73             
74             answer_field_name = 'exercise_%s' % exercise['id']
75             mark_field_name = 'markof_%s_by_%s' % (exercise['id'], request.user.id)
76             if exercise['type'] in ('open', 'file_upload') or exercise.get('open_part', None):
77                 if exercise['type'] == 'file_upload':
78                     try:
79                         attachment = Attachment.objects.get(submission = submission, exercise_id = exercise['id'])
80                     except Attachment.DoesNotExist:
81                         attachment = None
82                     widget = AttachmentWidget
83                     initial = attachment.file.url if attachment else None
84                 else:
85                     widget = forms.Textarea(attrs={'readonly':True})
86                     initial = get_open_answer(answers, exercise)
87
88                 fields[answer_field_name] = forms.CharField(
89                         widget = widget,
90                         initial = initial,
91                         label = 'Rozwiązanie zadania %s' % exercise['id']
92                 )
93
94                 fields[mark_field_name] = forms.ChoiceField(
95                     choices = [(None, '-')] + [(i,i) for i in range(exercise['max_points']+1)],
96                     initial = submission.get_mark(user_id = request.user.id, exercise_id = exercise['id']),
97                     label = u'Twoja ocena zadania %s' % exercise['id']
98                 )
99     return type('SubmissionForm', (SubmissionFormBase,), fields)
100
101
102 class SubmissionAdmin(admin.ModelAdmin):
103     list_display = ('__unicode__', 'todo',)
104     readonly_fields = readonly_fields
105
106     def get_form(self, request, obj, **kwargs):
107         return get_form(request, obj)
108     
109     def submitted_by(self, instance):
110         if instance.contact:
111             return '<a href="%s">%s</a>' % (
112                 reverse('admin:contact_contact_change', args = [instance.contact.id]),
113                 instance.contact.contact
114             )
115         return '-'
116     submitted_by.allow_tags = True
117     submitted_by.short_description = "Zgłoszony/a przez"
118
119     def todo(self, submission):
120         user = get_current_request().user
121         user_exercises = get_user_exercises(user)
122         user_marks = submission.marks.get(str(user.id), {})
123         return ','.join([str(e['id']) for e in user_exercises if str(e['id']) not in user_marks.keys()])
124
125     def save_model(self, request, submission, form, change):
126         for name, value in form.cleaned_data.items():
127             if name.startswith('markof_'):
128                 parts = name.split('_')
129                 exercise_id = parts[1]
130                 user_id = parts[3]
131                 submission.set_mark(user_id = user_id, exercise_id = exercise_id, mark = value)
132         submission.save()
133
134     def changelist_view(self, request, extra_context=None):
135         context = dict(examiners = [])
136         if request.user.is_superuser:
137             submissions = Submission.objects.all()
138             for assignment in Assignment.objects.all():
139                 examiner = dict(name = assignment.user.username, todo = 0)
140                 for submission in submissions:
141                     for exercise_id in assignment.exercises:
142                         if submission.get_mark(user_id = assignment.user.id, exercise_id = exercise_id) is None:
143                             examiner['todo'] += 1
144                 context['examiners'].append(examiner)
145         return super(SubmissionAdmin, self).changelist_view(request, extra_context = context)
146
147 admin.site.register(Submission, SubmissionAdmin)
148 admin.site.register(Assignment)