Getting cronjob to work from Django

July 19, 2017 106 views
Django Linux Commands Ubuntu 16.04

I have a droplet with Django installed and I can run a script from /home/sammy/revamp like python manage.py getimages it returns output like

Successfully found image for "6c90a52a75c5a91054937d6ab3c8cd4e.jpg"

Problem is it never runs itself from crontab -e

*/1 * * * * sammy cd /home/sammy/revamp/ && /usr/bin/python manage.py getimages >> /var/log/getimages.log

This is the last of many editing I've done to this log.

Btw here's it's code

class Command(BaseCommand):
    help = 'Update images coloured to database'

    def handle(self, *args, **options):
        #get filenames automatically
        try:
            images = listdir('/home/sammy/revamp/revamp/media/new_colour')

            for image_name in images:
                exists = Image.objects.filter(original_image='original/'+image_name)

                if exists:
                    image = exists[0]
                    image.colored_image = File( open('/home/sammy/revamp/revamp/media/new_colour/' + image_name, 'r'))
                    image.save()
                    os.remove('/home/sammy/revamp/revamp/media/new_colour/' + image_name)

                    self.stdout.write(self.style.SUCCESS('Successfully found image for "%s"' % image_name))

        except Exception, e:
            error_log = open('/home/sammy/revamp/error.log','a')
            error.write(str(e) + '\n')
            error.close()              

It should output something to error.log but also doesn't do this.

1 Answer

Hi @muirurisamuel

I'm not sure if you login to the console with root or the user sammy, but try running this command to make sure you're setting the cronjob for the specific user:

sudo crontab -u sammy -e

Then change the cronjob to this:

*/1 * * * * /usr/bin/python /home/sammy/revamp/manage.py getimages >> /var/log/getimages.log

And you can see the error log of the cron service by looking in the syslog log:

cat /var/log/syslog | grep "CRON"
Have another answer? Share your knowledge.