I'm Junior Django Dev. Got my first project. Doing quite well but senior dev that teaches me went on vacations....
I have a Task in my company to create a function that will remind all people in specyfic Group, 5 days before event by sending mail.
There is a TournamentModel
that contains a tournament_start_date
for instance '10.08.2018'
.
Player can join tournament, when he does he joins django group "Registered".
I have to create a function
(job?) that will check tournament_start_date
and if tournament begins in 5 days, this function will send emails to all people in "Registered" Group... automatically.
How can I do this? What should I use? How to run it and it will automatically check? I'm learning python/django for few months... but I meet jobs fot the first time ;/
I will appreciate any help.
If you break this down into two parts, it will be easier. The parts are
For the first part, I would begin by installing the outstanding django-extensions package so that it is easy to run scripts. (Check your INSTALLED_APPS, you may have it already.) Having the python-dateutil package will be helpful too.
Then I would write my script. Let's say your app is called "myapp". Create a directory under "myapp" called "scripts", and create an empty __init__.py in there.
Now create your script file in "myapp/scripts/remind_players.py". It will look something like this:
from datetime import date
from datutil.relativedelta import relativedelta
from django.mail import send_mail # I think this is right.
from myapp.models import Tournament
def run():
# find our tournaments that start five days from now.
for tournament in Tournament.objects.filter(tournament_start_date=date.today() + relativedelta(days=5)):
# find the players that are registered for the tournament
for player in tournament.registered_player_set():
send_mail(...)
To run your script manually, you would run
python manage.py runscript remind_players
(PROTIP: make sure that your test database only contains your own email address. It would be embarrassing to have your test system sending out emails to everyone.)
(PROTIP: you can also configure Django to put email messages in the logs, rather than actually sending them.)
For the second part, you'll have to find a way to schedule the job to run every day. Usually, your operating system will provide a way to do that. If you're on Unix/Linux, you'll use "cron". If you're on Windows, you'll use "Scheduled Tasks". (There are other options for scheduling, but these are the most common.)