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