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 django.views.decorators.http import require_POST
11 from unidecode import unidecode
13 from stage2.forms import AttachmentForm, MarkForm, AssignmentFieldForm
14 from stage2.models import Participant, Assignment, Answer, Attachment, Mark
17 def all_assignments(participant, sent_forms):
18 assignments = Assignment.objects.all()
20 sent_assignment, field_forms, attachment_forms = sent_forms
22 sent_assignment = field_forms = attachment_forms = None
23 for assignment in assignments:
24 assignment.answer, created = Answer.objects.get_or_create(participant=participant, assignment=assignment)
25 if assignment == sent_assignment:
26 assignment.field_forms = field_forms
27 assignment.attachment_forms = attachment_forms
29 assignment.field_forms = [
30 AssignmentFieldForm(label=label, field_no=i, options=options, answer=assignment.answer)
31 for i, (label, options) in enumerate(assignment.field_descriptions, 1)]
32 assignment.attachment_forms = [
33 (AttachmentForm(assignment=assignment, file_no=i, label=label, extensions=ext),
34 assignment.answer.attachment_set.filter(file_no=i).first() if assignment.answer else None)
35 for i, (label, ext) in enumerate(assignment.file_descriptions, 1)]
40 def participant_view(request, participant_id, key):
41 participant = get_object_or_404(Participant, id=participant_id)
42 if not participant.check(key):
47 for post_key, value in request.POST.iteritems():
48 if post_key.endswith('assignment_id'):
49 assignment_id = int(value)
52 assignment = get_object_or_404(Assignment, id=assignment_id)
54 if assignment.deadline < now:
55 raise Http404 # TODO za późno
59 for i, (label, ext) in enumerate(assignment.file_descriptions, 1):
60 answer, created = Answer.objects.get_or_create(participant=participant, assignment=assignment)
61 attachment, created = Attachment.objects.get_or_create(answer=answer, file_no=i)
62 form = AttachmentForm(
63 data=request.POST, files=request.FILES,
64 assignment=assignment, file_no=i, label=label, instance=attachment, extensions=ext)
69 attachment_forms.append(form)
70 for i, (label, options) in enumerate(assignment.field_descriptions, 1):
71 answer = Answer.objects.get(participant=participant, assignment=assignment)
72 form = AssignmentFieldForm(data=request.POST, label=label, field_no=i, options=options, answer=answer)
77 field_forms.append(form)
79 return HttpResponseRedirect(reverse('stage2_participant', args=(participant_id, key)))
81 sent_forms = (assignment, field_forms, attachment_forms)
84 response = render(request, 'stage2/participant.html', {
85 'participant': participant,
86 'assignments': all_assignments(participant, sent_forms)})
87 # not needed in Django 1.8
88 patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True)
92 def attachment_download(attachment):
93 response = HttpResponse(content_type='application/force-download')
94 response.write(attachment.file.read())
95 # workaround to this: https://code.djangoproject.com/ticket/20889
96 response['Content-Disposition'] = 'attachment; filename="%s"' % unidecode(attachment.filename().replace('\n', ' '))
97 response['Content-Length'] = response.tell()
101 def get_file(request, assignment_id, file_no, participant_id, key):
102 """We want to serve submitted files back to participants, but also validate their keys,
103 so static files are not good"""
104 participant = get_object_or_404(Participant, id=participant_id)
105 if not participant.check(key):
107 assignment = get_object_or_404(Assignment, id=assignment_id)
108 answer = get_object_or_404(Answer, participant=participant, assignment=assignment)
109 attachment = get_object_or_404(Attachment, answer=answer, file_no=file_no)
110 return attachment_download(attachment)
114 def assignment_list(request):
115 assignments = request.user.stage2_assignments.all()
117 return HttpResponseForbidden('Not allowed')
118 for assignment in assignments:
119 assignment.marked_count = Mark.objects.filter(expert=request.user, answer__assignment=assignment).count()
120 assignment.to_mark_count = assignment.available_answers(request.user).count()
121 assignment.supervisor = request.user in assignment.supervisors.all()
122 assignment.arbiter_count = assignment.answer_set.filter(need_arbiter=True).count()
124 non_empty_assignments = [ass for ass in assignments if ass.marked_count > 0 or ass.to_mark_count > 0]
125 if len(non_empty_assignments) == 1 and non_empty_assignments[0].to_mark_count > 0:
126 return HttpResponseRedirect(reverse('stage2_answer_list', args=[non_empty_assignments[0].id]))
127 return render(request, 'stage2/assignment_list.html', {'assignments': assignments})
130 def available_answers(assignment, expert, answer_with_errors=None, form_with_errors=None, marked=False):
132 answers = Answer.objects.filter(mark__expert=expert, assignment=assignment)
134 answers = assignment.available_answers(expert)
135 answers = answers.order_by('participant__last_name').prefetch_related('attachment_set')
136 for answer in answers:
137 attachments = answer.attachment_set.all()
138 attachments_by_file_no = {attachment.file_no: attachment for attachment in attachments}
139 answer.attachments = [
140 (desc, attachments_by_file_no.get(i))
141 for (i, (desc, ext)) in enumerate(assignment.file_descriptions, 1)]
142 if answer == answer_with_errors:
143 answer.form = form_with_errors
145 answer.form = MarkForm(
146 answer=answer, instance=answer.mark_set.filter(expert=expert).first(), prefix='ans%s' % answer.id)
151 def answer_list(request, assignment_id):
152 assignment = get_object_or_404(Assignment, id=assignment_id)
153 if request.user not in assignment.experts.all():
154 return HttpResponseForbidden('Not allowed')
155 return render(request, 'stage2/answer_list.html',
156 {'answers': available_answers(assignment, request.user), 'assignment': assignment})
160 def marked_answer_list(request, assignment_id):
161 assignment = get_object_or_404(Assignment, id=assignment_id)
162 if request.user not in assignment.experts.all():
163 return HttpResponseForbidden('Not allowed')
164 return render(request, 'stage2/answer_list.html', {
165 'answers': available_answers(assignment, request.user, marked=True),
166 'assignment': assignment,
172 def expert_download(request, attachment_id):
173 attachment = get_object_or_404(Attachment, id=attachment_id)
174 return attachment_download(attachment)
179 def mark_answer(request, answer_id):
180 answer = get_object_or_404(Answer, id=answer_id)
181 if request.user not in answer.assignment.experts.all():
182 return HttpResponseForbidden('Not allowed')
183 if answer.assignment.is_active():
184 return HttpResponseForbidden('Not allowed')
185 mark, created = Mark.objects.get_or_create(answer=answer, expert=request.user, defaults={'points': 0})
186 form = MarkForm(data=request.POST, answer=answer, instance=mark, prefix='ans%s' % answer.id)
192 return HttpResponseRedirect(reverse(
193 'stage2_answer_list' if created else 'stage2_marked_answers', args=[answer.assignment_id]))
197 def csv_results(request):
199 response = HttpResponse(content_type='text/csv')
200 writer = csv.writer(response)
201 assignments = Assignment.objects.all()
202 participants = Participant.objects.filter(complete_set=True)
203 headers = [u'imię', u'nazwisko', u'szkoła']
204 assignments_experts = []
205 for assignment in assignments:
206 for expert in assignment.experts.filter(mark__answer__assignment=assignment).distinct():
207 assignments_experts.append((assignment, expert))
208 headers.append(u'%s %s' % (assignment.title, expert.last_name))
209 for assignment in assignments:
210 headers.append(u'%s - średnia' % assignment.title.encode('utf-8'))
211 headers.append(u'ostateczny wynik')
212 writer.writerow([unicode(item).encode('utf-8') for item in headers])
213 for participant in participants:
215 participant.first_name,
216 participant.last_name,
217 participant.contact.body['school'],
219 for assignment, expert in assignments_experts:
223 expert=expert, answer__assignment=assignment, answer__participant=participant).points)
224 except Mark.DoesNotExist:
226 for assignment in assignments:
227 row.append('%.2f' % participant.answer_set.get(assignment=assignment).score())
228 row.append('%.2f' % participant.score())
229 writer.writerow([unicode(item).encode('utf-8') for item in row])
230 response['Content-Disposition'] = 'attachment; filename="wyniki.csv"'