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