1 # -*- coding: utf-8 -*-
3 from optparse import make_option
5 from collections import defaultdict
6 from django.core.management.base import BaseCommand
7 from wtem.management.commands import send_mail
8 from django.utils import translation
9 from django.template.loader import render_to_string
11 from wtem.models import Submission
14 def get_submissions():
15 return sorted(Submission.objects.exclude(answers=None), key=lambda s: -s.final_result)
21 class Command(BaseCommand):
23 option_list = BaseCommand.option_list + (
29 help='Send emails to teachers'),
35 help='Send emails to students'),
41 help='Send email only to one address'),
47 help='Print emails instead of sending them'),
51 super(Command, self).__init__()
52 self.sent = self.failed = None
55 def handle(self, *args, **options):
56 translation.activate('pl')
57 self.dummy = options['dummy']
58 for target in ['to_teachers', 'to_students']:
62 getattr(self, 'handle_' + target)(*args, **options)
64 def handle_to_students(self, *args, **options):
65 self.stdout.write('>>> Sending results to students')
66 subject = 'Wyniki I etapu Olimpiady Cyfrowej'
68 for submission in get_submissions():
69 if options['only_to'] and submission.email != options['only_to']:
71 final_result = submission.final_result
72 if final_result < minimum:
73 template = 'results_student_failed.txt'
75 template = 'results_student_passed.txt'
76 message = render_to_string('wtem/' + template, dict(final_result=submission.final_result))
77 self.send_message(message, subject, submission.email)
81 def handle_to_teachers(self, *args, **options):
82 self.stdout.write('>>> Sending results to teachers')
83 subject = 'Wyniki I etapu Olimpiady Cyfrowej'
85 submissions_by_contact = defaultdict(list)
87 for submission in get_submissions():
88 if options['only_to'] and submission.contact.contact != options['only_to']:
90 submissions_by_contact[submission.contact.contact].append(submission)
92 for contact_email, submissions in submissions_by_contact.items():
93 message = render_to_string('wtem/results_teacher.txt', dict(submissions=submissions))
94 self.send_message(message, subject, contact_email)
99 self.stdout.write('sent: %s, failed: %s' % (self.sent, self.failed))
101 def send_message(self, message, subject, email):
102 self.stdout.write('>>> sending results to %s' % email)
104 self.stdout.write(message)
108 send_mail(subject=subject, body=message, to=[email])
109 except BaseException, e:
111 self.stdout.write('failed sending to: ' + email + ': ' + str(e))
114 self.stdout.write('message sent to: ' + email)