In Django project we used management command in many cases.
Like, to create an application
python manage.py startapp my_app
To start webserver
python manage.py runserver
And there are other commands like this. But sometime we need to write a custom management command for our application that execute our own actions.
In a project directory there have a application my_app
Like, my_project/my_app/
Now in my_app
directory create a new directory called management
and add a _init__.py
blank file. Then inside management
directory create a new directory commands
and add a __init__.py
blank file.
Inside the commands
directory we will create our management script that will executable using manage.py
command.
Lets create a file inside commands
directory commands/date_now.py
First import BaseCommand
from django.core.management.base
and import datetime
. Now create a class Command
that extend BaseCommand
class and write a function called handle
. When we execute manage.py date_now
the handle function will run.
from django.core.management.base import BaseCommand
import datetime
class Command(BaseCommand):
def handle(self, *args, **options):
print datetime.datetime.now()
Now we can execute our management using
python manage.py date_now