1 # -*- coding: utf-8 -*-
3 from optparse import make_option
5 from django.core.management.base import BaseCommand
6 from wtem.management.commands import send_mail
7 from django.utils import translation
8 from django.template.loader import render_to_string
10 from wtem.models import Submission
13 def get_submissions():
14 return sorted(Submission.objects.exclude(answers=None).all(), key=lambda s: -s.final_result)
19 class Command(BaseCommand):
21 option_list = BaseCommand.option_list + (
27 help='Send emails to teachers'),
33 help='Send emails to students'),
39 help='Send email only to one address'),
43 super(Command, self).__init__()
44 self.sent = self.failed = None
46 def handle(self, *args, **options):
47 translation.activate('pl')
48 for target in ['to_teachers', 'to_students']:
52 getattr(self, 'handle_' + target)(*args, **options)
54 def handle_to_students(self, *args, **options):
55 self.stdout.write('>>> Sending results to students')
56 subject = 'Wyniki I etapu Olimpiady Cyfrowej'
58 for submission in get_submissions():
59 if options['only_to'] and submission.email != options['only_to']:
61 final_result = submission.final_result
62 if final_result < minimum:
63 template = 'results_student_failed.txt'
65 template = 'results_student_passed.txt'
66 message = render_to_string('wtem/' + template, dict(final_result=submission.final_result))
67 self.send_message(message, subject, submission.email)
71 def handle_to_teachers(self, *args, **options):
72 self.stdout.write('>>> Sending results to teachers')
73 subject = 'Wyniki I etapu Olimpiady Cyfrowej'
75 submissions_by_contact = dict()
77 for submission in get_submissions():
78 if options['only_to'] and submission.contact.contact != options['only_to']:
80 submissions_by_contact.setdefault(submission.contact.contact, []).append(submission)
82 for contact_email, submissions in submissions_by_contact.items():
83 message = render_to_string('wtem/results_teacher.txt', dict(submissions=submissions))
84 self.send_message(message, subject, contact_email)
89 self.stdout.write('sent: %s, failed: %s' % (self.sent, self.failed))
91 def send_message(self, message, subject, email):
92 self.stdout.write('>>> sending results to %s' % email)
94 send_mail(subject=subject, body=message, to=[email])
95 except BaseException, e:
97 self.stdout.write('failed sending to: ' + email + ': ' + str(e))
100 self.stdout.write('message sent to: ' + email)