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 contact.models import Contact
11 from wtem.models import Submission
14 def get_submissions():
15 return sorted(Submission.objects.exclude(answers=None).all(), 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 emails only to listed addresses'),
43 def handle(self, *args, **options):
44 translation.activate('pl')
45 for target in ['to_teachers', 'to_students']:
49 getattr(self, 'handle_' + target)(*args, **options)
51 def handle_to_students(self, *args, **options):
52 self.stdout.write('>>> Sending results to students')
53 subject = 'Wyniki II etapu Wielkiego Turnieju Edukacji Medialnej'
55 for submission in get_submissions():
56 if options['only_to'] and submission.email != options['only_to']:
58 final_result = submission.final_result
59 if final_result < minimum:
60 template = 'results_student_failed.txt'
62 template = 'results_student_passed.txt'
63 message = render_to_string('wtem/' + template, dict(final_result=submission.final_result))
64 self.send_message(message, subject, submission.email)
68 def handle_to_teachers(self, *args, **options):
69 self.stdout.write('>>> Sending results to teachers')
70 subject = 'Wyniki II etapu Wielkiego Turnieju Edukacji Medialnej'
73 submissions_by_contact = dict()
75 for submission in get_submissions():
76 if options['only_to'] and submission.contact.contact != options['only_to']:
78 submissions_by_contact.setdefault(submission.contact.id, []).append(submission)
80 for contact_id, submissions in submissions_by_contact.items():
81 contact = Contact.objects.get(id=contact_id)
82 message = render_to_string('wtem/results_teacher.txt', dict(submissions=submissions))
83 self.send_message(message, subject, contact.contact)
88 self.stdout.write('sent: %s, failed: %s' % (self.sent, self.failed))
90 def send_message(self, message, subject, email):
91 self.stdout.write('>>> sending results to %s' % email)
93 send_mail(subject=subject, body=message, to=[email])
94 except BaseException, e:
96 self.stdout.write('failed sending to: ' + email + ': ' + str(e))
99 self.stdout.write('message sent to: ' + email)