Django – Create custom django-admin command

We could manage our Django project by executing some commands which could be invoked through the manage.py. For example:

# Sync database
python manage.py syncdb

# Start the webserver
python manage.py runserver 0.0.0.0:8000

 

Not only this built-in commands, we can write our own command too.

1. Create a new Django project and in this example i called it custom_command. (Django 1.6.5)

django-admin.py startproject custom_command

 

2. Move to the project directory and create a new app.

# Move to the project directory
cd custom_command

# Create a new app and give a proper name, in this example scheduler.
python manage.py startapp scheduler

 

3. Move to the scheduler app folder and create some files as highlighted below. The __init__.py are just empty files.

custom_command
  + custom_command
  - manage.py
  - scheduler
    - __init__.py
    - admin.py
    - models.py
    - tests.py
    - views.py
    - management
      - __init__.py
      - commands
        - __init__.py
        - hello_world.py

 

4. Edit the hello_world.py.

from django.core.management.base import BaseCommand

class Command(BaseCommand):
  args = 'Arguments is not needed'
  help = 'Django admin custom command poc.'

  def handle(self, *args, **options):
    self.stdout.write("Hello World")

 

5. Include the scheduler app in custom_command/settings.py.

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'scheduler',
)

 

6. Move to the project root and generate the db.sqlite3.

python manage.py syncdb

 

7. Your hello_world command is ready! You could check the help message by:

python manage.py help hello_world

django-custom-command-1
 

8. Run the hello_world command.

python manage.py hello_world

django-custom-command-2
 

The custom command could also take input parameters as well as different options. For more details, please refer to the official documentation below.

Done =)

Reference: Django 1.6 – Writing custom django-admin commands

Advertisements

4 thoughts on “Django – Create custom django-admin command”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s