1 # -*- coding: utf-8 -*-
2 from django.contrib.auth.decorators import login_required
3 from django.core.urlresolvers import reverse
4 from django.http import Http404
5 from django.http.response import HttpResponseRedirect, HttpResponse, HttpResponseForbidden
6 from django.shortcuts import get_object_or_404, render
7 from django.utils import timezone
8 from django.utils.cache import patch_cache_control
9 from django.views.decorators.cache import never_cache
10 from unidecode import unidecode
12 from stage2.forms import AttachmentForm, MarkForm, AssignmentFieldForm
13 from stage2.models import Participant, Assignment, Answer, Attachment, Mark
16 def all_assignments(participant, sent_forms):
17 assignments = Assignment.objects.all()
19 sent_assignment, field_forms, attachment_forms = sent_forms
21 sent_assignment = field_forms = attachment_forms = None
22 for assignment in assignments:
23 assignment.answer, created = Answer.objects.get_or_create(participant=participant, assignment=assignment)
24 if assignment == sent_assignment:
25 assignment.field_forms = field_forms
26 assignment.attachment_forms = attachment_forms
28 assignment.field_forms = [
29 AssignmentFieldForm(label=label, field_no=i, options=options, answer=assignment.answer)
30 for i, (label, options) in enumerate(assignment.field_descriptions, 1)]
31 assignment.attachment_forms = [
32 (AttachmentForm(assignment=assignment, file_no=i, label=label, extensions=ext),
33 assignment.answer.attachment_set.filter(file_no=i).first() if assignment.answer else None)
34 for i, (label, ext) in enumerate(assignment.file_descriptions, 1)]
39 def participant_view(request, participant_id, key):
40 participant = get_object_or_404(Participant, id=participant_id)
41 if not participant.check(key):
46 for post_key, value in request.POST.iteritems():
47 if post_key.endswith('assignment_id'):
48 assignment_id = int(value)
51 assignment = get_object_or_404(Assignment, id=assignment_id)
53 if assignment.deadline < now:
54 return HttpResponseForbidden('Not Allowed')
55 attachments_valid, attachment_forms = get_attachment_forms(assignment, participant, request)
56 fields_valid, field_forms = get_field_forms(assignment, participant, request)
57 if attachments_valid and fields_valid:
58 return HttpResponseRedirect(reverse('stage2_participant', args=(participant_id, key)))
60 sent_forms = (assignment, field_forms, attachment_forms)
63 response = render(request, 'stage2/participant.html', {
64 'participant': participant,
65 'assignments': all_assignments(participant, sent_forms)})
66 # not needed in Django 1.8
67 patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True)
71 def get_attachment_forms(assignment, participant, request):
74 for i, (label, ext) in enumerate(assignment.file_descriptions, 1):
75 answer, created = Answer.objects.get_or_create(participant=participant, assignment=assignment)
76 attachment, created = Attachment.objects.get_or_create(answer=answer, file_no=i)
77 form = AttachmentForm(
78 data=request.POST, files=request.FILES,
79 assignment=assignment, file_no=i, label=label, instance=attachment, extensions=ext)
84 attachment_forms.append(form)
85 return all_valid, attachment_forms
88 def get_field_forms(assignment, participant, request):
91 for i, (label, options) in enumerate(assignment.field_descriptions, 1):
92 answer = Answer.objects.get(participant=participant, assignment=assignment)
93 form = AssignmentFieldForm(data=request.POST, label=label, field_no=i, options=options, answer=answer)
98 field_forms.append(form)
99 return all_valid, field_forms
102 def attachment_download(attachment):
103 response = HttpResponse(content_type='application/force-download')
104 response.write(attachment.file.read())
105 # workaround to this: https://code.djangoproject.com/ticket/20889
106 response['Content-Disposition'] = 'attachment; filename="%s"' % unidecode(attachment.filename().replace('\n', ' '))
107 response['Content-Length'] = response.tell()
111 def get_file(request, assignment_id, file_no, participant_id, key):
112 """We want to serve submitted files back to participants, but also validate their keys,
113 so static files are not good"""
114 participant = get_object_or_404(Participant, id=participant_id)
115 if not participant.check(key):
117 assignment = get_object_or_404(Assignment, id=assignment_id)
118 answer = get_object_or_404(Answer, participant=participant, assignment=assignment)
119 attachment = get_object_or_404(Attachment, answer=answer, file_no=file_no)
120 return attachment_download(attachment)
124 def assignment_list(request):
125 expert = request.user
126 assignments = expert.stage2_assignments.all()
128 return HttpResponseForbidden('Not allowed')
129 for assignment in assignments:
130 assignment.marked_count = assignment.available_answers(expert, marked=True).count()
131 assignment.to_mark_count = assignment.available_answers(expert).count()
132 assignment.supervisor = expert in assignment.supervisors.all()
133 assignment.arbiter_count = assignment.needing_arbiter().count()
135 non_empty_assignments = [ass for ass in assignments if ass.marked_count > 0 or ass.to_mark_count > 0]
136 if len(non_empty_assignments) == 1 and non_empty_assignments[0].to_mark_count > 0:
137 return HttpResponseRedirect(reverse('stage2_answer_list', args=[non_empty_assignments[0].id]))
138 return render(request, 'stage2/assignment_list.html', {'assignments': assignments})
141 def available_answers(assignment, expert, sent_forms=None, marked=False):
143 answers = assignment.available_answers(expert, marked=True)
145 answers = assignment.available_answers(expert).order_by('participant__last_name')
146 answers = answers.prefetch_related('attachment_set')
148 sent_answer_id, mark_forms = sent_forms
150 sent_answer_id = mark_forms = None
151 for answer in answers:
152 attachments = answer.attachment_set.all()
153 attachments_by_file_no = {attachment.file_no: attachment for attachment in attachments}
154 answer.attachments = [
155 (desc, attachments_by_file_no.get(i))
156 for (i, (desc, ext)) in enumerate(assignment.file_descriptions, 1)]
157 if answer.id == sent_answer_id:
158 answer.forms = mark_forms
161 for criterion in assignment.markcriterion_set.all():
162 answer.forms.append(MarkForm(
165 instance=answer.mark_set.filter(expert=expert, criterion=criterion).first(),
166 prefix='mark%s-%s' % (answer.id, criterion.id)))
171 def answer_list(request, assignment_id, marked=False):
172 assignment = get_object_or_404(Assignment, id=assignment_id)
173 expert = request.user
174 if expert not in assignment.experts.all():
175 return HttpResponseForbidden('Not allowed')
179 for post_key, value in request.POST.iteritems():
180 if post_key.endswith('answer_id'):
181 answer_id = int(value)
182 answer = get_object_or_404(Answer, id=answer_id)
184 if answer not in assignment.available_answers(expert, marked=marked):
185 return HttpResponseForbidden('Not allowed')
186 if answer.assignment.is_active():
187 return HttpResponseForbidden('Not allowed')
188 all_valid, forms = get_mark_forms(answer, request)
191 return HttpResponseRedirect(reverse('stage2_marked_answers', args=[answer.assignment_id]))
193 return HttpResponseRedirect(reverse('stage2_answer_list', args=[answer.assignment_id]))
195 sent_forms = answer_id, forms
198 answers = available_answers(assignment, expert, sent_forms=sent_forms, marked=marked)
199 return render(request, 'stage2/answer_list.html', {
201 'assignment': assignment,
202 'field_counts': assignment.field_counts(answers) if not marked else None,
203 'supervisor': expert in assignment.supervisors.all(),
208 def get_mark_forms(answer, request):
212 for criterion in answer.assignment.markcriterion_set.all():
213 mark, created = Mark.objects.get_or_create(
214 answer=answer, criterion=criterion, expert=request.user, defaults={'points': 0})
216 created_marks.append(mark)
218 data=request.POST, answer=answer, criterion=criterion, instance=mark,
219 prefix='mark%s-%s' % (answer.id, criterion.id))
226 for mark in created_marks:
228 return all_valid, forms
232 def expert_download(request, attachment_id):
233 attachment = get_object_or_404(Attachment, id=attachment_id)
234 return attachment_download(attachment)
238 def csv_results(request):
240 response = HttpResponse(content_type='text/csv')
241 writer = csv.writer(response)
242 assignments = Assignment.objects.all()
243 participants = Participant.objects.filter(complete_set=True)
244 headers = [u'imię', u'nazwisko', u'szkoła']
245 assignments_experts = []
246 for assignment in assignments:
247 for expert in assignment.experts.filter(mark__answer__assignment=assignment).distinct():
248 assignments_experts.append((assignment, expert))
249 headers.append(u'%s %s' % (assignment.title, expert.last_name))
250 for assignment in assignments:
251 headers.append(u'%s - średnia' % assignment.title.encode('utf-8'))
252 headers.append(u'ostateczny wynik')
253 writer.writerow([unicode(item).encode('utf-8') for item in headers])
254 for participant in participants:
256 participant.first_name,
257 participant.last_name,
258 participant.contact.body['school'],
260 for assignment, expert in assignments_experts:
264 expert=expert, answer__assignment=assignment, answer__participant=participant).points)
265 except Mark.DoesNotExist:
267 for assignment in assignments:
268 row.append('%.2f' % participant.answer_set.get(assignment=assignment).score())
269 row.append('%.2f' % participant.score())
270 writer.writerow([unicode(item).encode('utf-8') for item in row])
271 response['Content-Disposition'] = 'attachment; filename="wyniki.csv"'