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