pythondjangoemailcron

How to schedule a daily report to be sent out as email


I want to know how exactly I can schedule a report to be generated and sent out as email of the visitor details log table on a daily basis at a particular time. The visitor details like name, in and out time, purpose of visit needs to be sent out as an email. I'm using Django 1.6.5 on linux.

I am aware of cron Set up a scheduled job? https://docs.djangoproject.com/en/dev/howto/custom-management-commands/ but don't seem to get the things together.

I can create template and view in the Django admin GUI using all the model admin options. I can also generate CSV using actions in the admin panel. However, I want the report to be generated automatically every day and sent out as email without logging in Django. I need a complete code solution for that, as I am not clear how this can be done.


Solution

  • First create custom management command like:

    class Command(BaseCommand):
    
    commands = ['sendreport',]
    args = '[command]'
    help = 'Send report'
    
    def handle(self, *args, **options):
    
        '''
        Get completed sessions, send invite to vote
        '''
    
        reports = Log.objects.filter(date__gt=datetime.today(),date__lt=(datetime.today()+timedelta(days=2)))
        for report in reports:
            send_notification(_("Report"), _("log:%s")%report.text, 'my@email.com' )
    

    To create email text and send

    Then you can add cronjob, something like

    0 0 * * * /pathtovirtualenv/python manage.py sendreport
    

    To run this command every night