1 # -*- coding: utf-8 -*-
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 from django.conf.urls import url, patterns
11 from django.shortcuts import render
12 from django.contrib.auth.models import User
13 from django.http import HttpResponse
14 from django.template.loader import render_to_string
15 from .models import Submission, Assignment, Attachment, exercises
16 from .middleware import get_current_request
19 def get_user_exercises(user):
21 assignment = Assignment.objects.get(user = user)
22 return [e for e in exercises if e['id'] in assignment.exercises]
23 except Assignment.DoesNotExist:
27 readonly_fields = ('submitted_by', 'first_name', 'last_name', 'email', 'key', 'key_sent')
29 class AttachmentWidget(forms.Widget):
30 def render(self, name, value, *args, **kwargs):
32 a_tag = '<a href="%s">%s</a>' % (value, value)
35 return mark_safe(('<input type="hidden" name="%s" value="%s"/>' + a_tag) % (name, value))
37 class SubmissionFormBase(forms.ModelForm):
40 exclude = ('answers', 'marks', 'contact') + readonly_fields
43 def get_open_answer(answers, exercise):
44 def get_option(options, id):
45 for option in options:
46 if option['id'] == int(id):
49 exercise_id = str(exercise['id'])
50 answer = answers[exercise_id]
51 if exercise['type'] == 'open':
52 if isinstance(answer, list):
55 field = get_option(exercise['fields'], part['id'])
56 toret += '- %s:\n\n%s\n\n' % (field['caption'], part['text'])
59 if exercise['type'] == 'edumed_wybor':
60 ok = set(map(str, exercise['answer'])) == set(map(str,answer['closed_part']))
61 toret = u'Czesc testowa [%s]:\n' % ('poprawna' if ok else 'niepoprawna')
62 for selected in answer['closed_part']:
63 option = get_option(exercise['options'], selected)
64 toret += '%s: %s\n' % (selected, option['text'])
66 toret += u'<nie wybrano odpowiedzi>\n'
67 toret += u'\nCzesc otwarta (%s):\n\n' % ' '.join(exercise['open_part'])
68 toret += answer['open_part']
73 def get_form(request, submission):
75 if submission.answers:
76 answers = simplejson.loads(submission.answers)
77 user_exercises = get_user_exercises(request.user)
78 for exercise in exercises:
79 if exercise not in user_exercises:
82 answer_field_name = 'exercise_%s' % exercise['id']
83 mark_field_name = 'markof_%s_by_%s' % (exercise['id'], request.user.id)
84 if exercise['type'] in ('open', 'file_upload') or exercise.get('open_part', None):
85 if exercise['type'] == 'file_upload':
87 attachment = Attachment.objects.get(submission = submission, exercise_id = exercise['id'])
88 except Attachment.DoesNotExist:
90 widget = AttachmentWidget
91 initial = attachment.file.url if attachment else None
93 widget = forms.Textarea(attrs={'readonly':True})
94 initial = get_open_answer(answers, exercise)
96 fields[answer_field_name] = forms.CharField(
99 label = 'Rozwiązanie zadania %s' % exercise['id']
102 fields[mark_field_name] = forms.ChoiceField(
103 choices = [(None, '-')] + [(i,i) for i in range(exercise['max_points']+1)],
104 initial = submission.get_mark(user_id = request.user.id, exercise_id = exercise['id']),
105 label = u'Twoja ocena zadania %s' % exercise['id']
108 if not request.user.is_superuser:
109 class Meta(SubmissionFormBase.Meta):
111 Meta.exclude += ('examiners',)
112 fields['Meta'] = Meta
114 return type('SubmissionForm', (SubmissionFormBase,), fields)
117 class SubmissionAdmin(admin.ModelAdmin):
118 list_display = ('__unicode__', 'todo', 'examiners_repr')
119 readonly_fields = readonly_fields
121 def get_form(self, request, obj, **kwargs):
122 return get_form(request, obj)
124 def submitted_by(self, instance):
126 return '<a href="%s">%s</a>' % (
127 reverse('admin:contact_contact_change', args = [instance.contact.id]),
128 instance.contact.contact
131 submitted_by.allow_tags = True
132 submitted_by.short_description = "Zgłoszony/a przez"
134 def todo(self, submission):
135 user = get_current_request().user
136 user_exercises = get_user_exercises(user)
137 user_marks = submission.marks.get(str(user.id), {})
138 return ','.join([str(e['id']) for e in user_exercises if str(e['id']) not in user_marks.keys()])
139 todo.short_description = 'Twoje nieocenione zadania'
141 def examiners_repr(self, submission):
142 return ', '.join([u.username for u in submission.examiners.all()])
143 examiners_repr.short_description = 'Przypisani do zgłoszenia'
145 def save_model(self, request, submission, form, change):
146 for name, value in form.cleaned_data.items():
147 if name.startswith('markof_'):
148 parts = name.split('_')
149 exercise_id = parts[1]
151 submission.set_mark(user_id = user_id, exercise_id = exercise_id, mark = value)
154 def changelist_view(self, request, extra_context=None):
155 context = dict(examiners = [])
156 assignments = Assignment.objects.all()
157 if not request.user.is_superuser:
158 assignments = assignments.filter(user = request.user)
159 for assignment in assignments:
160 examiner = dict(name = assignment.user.username, todo = 0)
161 for submission in Submission.objects.filter(examiners = assignment.user):
162 for exercise_id in assignment.exercises:
163 if submission.get_mark(user_id = assignment.user.id, exercise_id = exercise_id) is None:
164 examiner['todo'] += 1
165 context['examiners'].append(examiner)
166 return super(SubmissionAdmin, self).changelist_view(request, extra_context = context)
168 def queryset(self, request):
169 qs = super(SubmissionAdmin, self).queryset(request)
170 if not request.user.is_superuser:
171 qs = qs.filter(examiners = request.user)
175 urls = super(SubmissionAdmin, self).get_urls()
177 url(r'^report/$', self.admin_site.admin_view(report_view), name='wtem_admin_report')
178 ) + super(SubmissionAdmin, self).get_urls()
181 class SubmissionsSet:
182 def __init__(self, submissions):
183 self.submissions = submissions
184 self.examiners_by_exercise = dict()
185 for submission in submissions:
186 for user_id, marks in submission.marks.items():
187 user = User.objects.get(pk=user_id)
188 for exercise_id in marks.keys():
189 examiners = self.examiners_by_exercise.setdefault(exercise_id, [])
190 if not user in examiners:
191 examiners.append(user)
193 def report_view(request):
194 submissions = sorted(Submission.objects.all(), key = lambda s: -s.final_result)
195 toret = render_to_string('wtem/admin_report.csv', dict(
196 submissionsSet = SubmissionsSet(submissions),
197 exercise_ids = map(str, range(1,len(exercises)+1))
199 response = HttpResponse(toret, content_type = 'text/csv')
200 response['Content-Disposition'] = 'attachment; filename="wyniki.csv"'
203 admin.site.register(Submission, SubmissionAdmin)
204 admin.site.register(Assignment)