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"/>' % (name, value)) + a_tag)
37 class TextareaWithLinks(forms.Textarea):
38 def render(self, name, value, *args, **kwargs):
41 output = super(TextareaWithLinks, self).render(name, t, *args, **kwargs)
42 moreoutput = "<div style='margin-left: 106px'>"
44 moreoutput += u"<br>%s: %s" % (k, AttachmentWidget().render(n, v))
45 output += mark_safe(moreoutput + "</div>")
48 class SubmissionFormBase(forms.ModelForm):
51 exclude = ('answers', 'marks', 'contact', 'end_time') + readonly_fields
54 def get_open_answer(answers, exercise):
55 def get_option(options, id):
56 for option in options:
57 if str(option['id']) == id:
60 exercise_id = str(exercise['id'])
61 answer = answers[exercise_id]
62 if exercise['type'] == 'open':
63 if isinstance(answer, list):
66 field = get_option(exercise['fields'], part['id'])
67 toret += '- %s:\n\n%s\n\n' % (field['caption'], part['text'])
70 if exercise['type'] == 'edumed_wybor':
71 ok = set(map(str, exercise['answer'])) == set(map(str,answer['closed_part']))
72 toret = u'Czesc testowa [%s]:\n' % ('poprawna' if ok else 'niepoprawna')
73 if len(answer['closed_part']):
74 for selected in answer['closed_part']:
75 option = get_option(exercise['options'], selected)
76 toret += '%s: %s\n' % (selected, option['text'])
78 toret += u'<nie wybrano odpowiedzi>\n'
79 toret += u'\nCzesc otwarta (%s):\n\n' % ' '.join(exercise['open_part'])
80 toret += answer['open_part']
85 def get_form(request, submission):
87 if submission.answers:
88 answers = simplejson.loads(submission.answers)
89 user_exercises = get_user_exercises(request.user)
90 for exercise in exercises:
91 if exercise not in user_exercises:
94 answer_field_name = 'exercise_%s' % exercise['id']
95 mark_field_name = 'markof_%s_by_%s' % (exercise['id'], request.user.id)
96 if exercise['type'] in ('open', 'file_upload') or exercise.get('open_part', None):
97 if exercise['type'] == 'file_upload':
99 attachment = Attachment.objects.get(submission = submission, exercise_id = exercise['id'])
100 except Attachment.DoesNotExist:
102 widget = AttachmentWidget
103 initial = attachment.file.url if attachment else None
105 #widget = forms.Textarea(attrs={'readonly':True})
106 widget = TextareaWithLinks(attrs={'readonly':True})
109 for qfield in exercise.get('fields', []):
110 if qfield.get('type') == 'file':
111 qfiles.append((qfield['id'], qfield['caption']))
113 eid = int(exercise['id'])
115 for att in Attachment.objects.filter(submission=submission, exercise_id=eid).order_by('tag'):
116 by_tag[att.tag] = att.file.url
117 for tag, caption in qfiles:
120 links.append((caption, "file_%s__%s" % (eid, tag), v))
121 initial = get_open_answer(answers, exercise), links
123 fields[answer_field_name] = forms.CharField(
126 label = u'Rozwiązanie zadania %s' % exercise['id'],
130 choices = [(None, '-')] # + [(i,i) for i in range(exercise['max_points']+1)],
132 while i <= exercise['max_points']:
133 choices.append((i, i))
135 fields[mark_field_name] = forms.ChoiceField(
137 initial = submission.get_mark(user_id = request.user.id, exercise_id = exercise['id']),
138 label = u'Twoja ocena zadania %s' % exercise['id']
141 if not request.user.is_superuser:
142 class Meta(SubmissionFormBase.Meta):
144 Meta.exclude += ('examiners',)
145 fields['Meta'] = Meta
147 return type('SubmissionForm', (SubmissionFormBase,), fields)
150 class SubmissionAdmin(admin.ModelAdmin):
151 list_display = ('__unicode__', 'todo', 'examiners_repr')
152 readonly_fields = readonly_fields
154 def get_form(self, request, obj, **kwargs):
155 return get_form(request, obj)
157 def submitted_by(self, instance):
159 return '<a href="%s">%s</a>' % (
160 reverse('admin:contact_contact_change', args = [instance.contact.id]),
161 instance.contact.contact
164 submitted_by.allow_tags = True
165 submitted_by.short_description = "Zgłoszony/a przez"
167 def todo(self, submission):
168 user = get_current_request().user
169 user_exercises = get_user_exercises(user)
170 user_marks = submission.marks.get(str(user.id), {})
171 return ','.join([str(e['id']) for e in user_exercises if str(e['id']) not in user_marks.keys()])
172 todo.short_description = 'Twoje nieocenione zadania'
174 def examiners_repr(self, submission):
175 return ', '.join([u.username for u in submission.examiners.all()])
176 examiners_repr.short_description = 'Przypisani do zgłoszenia'
178 def save_model(self, request, submission, form, change):
179 for name, value in form.cleaned_data.items():
180 if name.startswith('markof_'):
181 parts = name.split('_')
182 exercise_id = parts[1]
184 submission.set_mark(user_id = user_id, exercise_id = exercise_id, mark = value)
187 def changelist_view(self, request, extra_context=None):
188 context = dict(examiners = [])
189 assignments = Assignment.objects.all()
190 if not request.user.is_superuser:
191 assignments = assignments.filter(user = request.user)
192 for assignment in assignments:
193 examiner = dict(name = assignment.user.username, todo = 0)
194 for submission in Submission.objects.filter(examiners = assignment.user):
195 for exercise_id in assignment.exercises:
196 if submission.get_mark(user_id = assignment.user.id, exercise_id = exercise_id) is None:
197 examiner['todo'] += 1
198 context['examiners'].append(examiner)
199 return super(SubmissionAdmin, self).changelist_view(request, extra_context = context)
201 def queryset(self, request):
202 qs = super(SubmissionAdmin, self).queryset(request)
203 if not request.user.is_superuser:
204 qs = qs.filter(examiners = request.user)
208 urls = super(SubmissionAdmin, self).get_urls()
210 url(r'^report/$', self.admin_site.admin_view(report_view), name='wtem_admin_report')
211 ) + super(SubmissionAdmin, self).get_urls()
214 class SubmissionsSet:
215 def __init__(self, submissions):
216 self.submissions = submissions
217 self.examiners_by_exercise = dict()
218 for submission in submissions:
219 for user_id, marks in submission.marks.items():
220 user = User.objects.get(pk=user_id)
221 for exercise_id in marks.keys():
222 examiners = self.examiners_by_exercise.setdefault(exercise_id, [])
223 if not user in examiners:
224 examiners.append(user)
226 def report_view(request):
227 submissions = sorted(Submission.objects.all(), key = lambda s: -s.final_result)
228 toret = render_to_string('wtem/admin_report.csv', dict(
229 submissionsSet = SubmissionsSet(submissions),
230 #exercise_ids = map(str, range(1,len(exercises)+1))
231 exercise_ids = [str(e['id']) for e in exercises]
233 response = HttpResponse(toret, content_type = 'text/csv')
234 response['Content-Disposition'] = 'attachment; filename="wyniki.csv"'
237 admin.site.register(Submission, SubmissionAdmin)
238 admin.site.register(Assignment)