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', 'end_time') + 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 if len(answer['closed_part']):
63 for selected in answer['closed_part']:
64 option = get_option(exercise['options'], selected)
65 toret += '%s: %s\n' % (selected, option['text'])
67 toret += u'<nie wybrano odpowiedzi>\n'
68 toret += u'\nCzesc otwarta (%s):\n\n' % ' '.join(exercise['open_part'])
69 toret += answer['open_part']
74 def get_form(request, submission):
76 if submission.answers:
77 answers = simplejson.loads(submission.answers)
78 user_exercises = get_user_exercises(request.user)
79 for exercise in exercises:
80 if exercise not in user_exercises:
83 answer_field_name = 'exercise_%s' % exercise['id']
84 mark_field_name = 'markof_%s_by_%s' % (exercise['id'], request.user.id)
85 if exercise['type'] in ('open', 'file_upload') or exercise.get('open_part', None):
86 if exercise['type'] == 'file_upload':
88 attachment = Attachment.objects.get(submission = submission, exercise_id = exercise['id'])
89 except Attachment.DoesNotExist:
91 widget = AttachmentWidget
92 initial = attachment.file.url if attachment else None
94 widget = forms.Textarea(attrs={'readonly':True})
95 initial = get_open_answer(answers, exercise)
97 fields[answer_field_name] = forms.CharField(
100 label = 'Rozwiązanie zadania %s' % exercise['id']
103 fields[mark_field_name] = forms.ChoiceField(
104 choices = [(None, '-')] + [(i,i) for i in range(exercise['max_points']+1)],
105 initial = submission.get_mark(user_id = request.user.id, exercise_id = exercise['id']),
106 label = u'Twoja ocena zadania %s' % exercise['id']
109 if not request.user.is_superuser:
110 class Meta(SubmissionFormBase.Meta):
112 Meta.exclude += ('examiners',)
113 fields['Meta'] = Meta
115 return type('SubmissionForm', (SubmissionFormBase,), fields)
118 class SubmissionAdmin(admin.ModelAdmin):
119 list_display = ('__unicode__', 'todo', 'examiners_repr')
120 readonly_fields = readonly_fields
122 def get_form(self, request, obj, **kwargs):
123 return get_form(request, obj)
125 def submitted_by(self, instance):
127 return '<a href="%s">%s</a>' % (
128 reverse('admin:contact_contact_change', args = [instance.contact.id]),
129 instance.contact.contact
132 submitted_by.allow_tags = True
133 submitted_by.short_description = "Zgłoszony/a przez"
135 def todo(self, submission):
136 user = get_current_request().user
137 user_exercises = get_user_exercises(user)
138 user_marks = submission.marks.get(str(user.id), {})
139 return ','.join([str(e['id']) for e in user_exercises if str(e['id']) not in user_marks.keys()])
140 todo.short_description = 'Twoje nieocenione zadania'
142 def examiners_repr(self, submission):
143 return ', '.join([u.username for u in submission.examiners.all()])
144 examiners_repr.short_description = 'Przypisani do zgłoszenia'
146 def save_model(self, request, submission, form, change):
147 for name, value in form.cleaned_data.items():
148 if name.startswith('markof_'):
149 parts = name.split('_')
150 exercise_id = parts[1]
152 submission.set_mark(user_id = user_id, exercise_id = exercise_id, mark = value)
155 def changelist_view(self, request, extra_context=None):
156 context = dict(examiners = [])
157 assignments = Assignment.objects.all()
158 if not request.user.is_superuser:
159 assignments = assignments.filter(user = request.user)
160 for assignment in assignments:
161 examiner = dict(name = assignment.user.username, todo = 0)
162 for submission in Submission.objects.filter(examiners = assignment.user):
163 for exercise_id in assignment.exercises:
164 if submission.get_mark(user_id = assignment.user.id, exercise_id = exercise_id) is None:
165 examiner['todo'] += 1
166 context['examiners'].append(examiner)
167 return super(SubmissionAdmin, self).changelist_view(request, extra_context = context)
169 def queryset(self, request):
170 qs = super(SubmissionAdmin, self).queryset(request)
171 if not request.user.is_superuser:
172 qs = qs.filter(examiners = request.user)
176 urls = super(SubmissionAdmin, self).get_urls()
178 url(r'^report/$', self.admin_site.admin_view(report_view), name='wtem_admin_report')
179 ) + super(SubmissionAdmin, self).get_urls()
182 class SubmissionsSet:
183 def __init__(self, submissions):
184 self.submissions = submissions
185 self.examiners_by_exercise = dict()
186 for submission in submissions:
187 for user_id, marks in submission.marks.items():
188 user = User.objects.get(pk=user_id)
189 for exercise_id in marks.keys():
190 examiners = self.examiners_by_exercise.setdefault(exercise_id, [])
191 if not user in examiners:
192 examiners.append(user)
194 def report_view(request):
195 submissions = sorted(Submission.objects.all(), key = lambda s: -s.final_result)
196 toret = render_to_string('wtem/admin_report.csv', dict(
197 submissionsSet = SubmissionsSet(submissions),
198 exercise_ids = map(str, range(1,len(exercises)+1))
200 response = HttpResponse(toret, content_type = 'text/csv')
201 response['Content-Disposition'] = 'attachment; filename="wyniki.csv"'
204 admin.site.register(Submission, SubmissionAdmin)
205 admin.site.register(Assignment)