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)
20 class Command(BaseCommand):
22 option_list = BaseCommand.option_list + (
28 help='Send emails to teachers'),
34 help='Send emails to students'),
40 help='Send email only to one address'),
46 help='Print emails instead of sending them'),
50 super(Command, self).__init__()
51 self.sent = self.failed = None
54 def handle(self, *args, **options):
55 translation.activate('pl')
56 self.dummy = options['dummy']
57 for target in ['to_teachers', 'to_students']:
61 getattr(self, 'handle_' + target)(*args, **options)
63 def handle_to_students(self, *args, **options):
64 self.stdout.write('>>> Sending results to students')
65 subject = 'Wyniki I etapu Olimpiady Cyfrowej'
67 for submission in get_submissions():
68 if options['only_to'] and submission.email != options['only_to']:
70 final_result = submission.final_result
71 if final_result < minimum:
72 template = 'results_student_failed.txt'
74 template = 'results_student_passed.txt'
75 message = render_to_string('wtem/' + template, dict(final_result=submission.final_result))
76 self.send_message(message, subject, submission.email)
80 def handle_to_teachers(self, *args, **options):
81 self.stdout.write('>>> Sending results to teachers')
82 subject = 'Wyniki I etapu Olimpiady Cyfrowej'
84 submissions_by_contact = defaultdict(list)
86 for submission in get_submissions():
87 if options['only_to'] and submission.contact.contact != options['only_to']:
89 submissions_by_contact[submission.contact.contact].append(submission)
91 for contact_email, submissions in submissions_by_contact.items():
92 message = render_to_string('wtem/results_teacher.txt', dict(submissions=submissions))
93 self.send_message(message, subject, contact_email)
98 self.stdout.write('sent: %s, failed: %s' % (self.sent, self.failed))
100 def send_message(self, message, subject, email):
101 self.stdout.write('>>> sending results to %s' % email)
103 self.stdout.write(message)
107 send_mail(subject=subject, body=message, to=[email])
108 except BaseException, e:
110 self.stdout.write('failed sending to: ' + email + ': ' + str(e))
113 self.stdout.write('message sent to: ' + email)