In Django it is very straight forward to add extra commands to the manage.py and django-admin.py scripts. The Django Documentation describes the process but gives no examples. I like examples so I’m writing this for others.
In the past I’d add these to make stand alone scripts that used the Django libraries.
from django.conf import settings
from django.core.management import setup_environ
setup_environ( settings )
The method works well but I find it cleaner to add commands to the manage and django-admin scripts instead of having several stand alone scripts. The desired effect is to be able to run
$ ./manage.py your_command_name
instead of python your_command_name.py. Big difference? No… But I think on a large project it adds organization and its some sort of a standard in the event that others will be using your code.
In the app which the command is used for make the following directory structure:
management/
__init__.py
commands/
__init__.py
your_command_name.py
Then in your file (your_command_name.py) paste the following code, puting the functions to run in the handle_noargs function.
from django.core.management.base import NoArgsCommand
class Command(NoArgsCommand):
help = “Describe the Command Here”
def handle_noargs(self, **options):
< your code here >
That’s it! You can also do some more complicated functionality with command options. Take a look at commands listed in /django/core/management/commands for examples there.
Posted by Damien on June 11, 2009 at 2:17 am
Hello,
Are there some reserved names ? Or a cache that I’d have to reload to have access to the command ?
I’ve followed your instructions. But the command is still not found
Posted by godavemon on June 11, 2009 at 8:22 pm
There are some reserved commands but “drop” is not one of them.
Make sure that you have the file structure listed above inside one of your app directories and make sure that that app is listed inside the INSTALLED_APPS in your settings.py
Additionally make sure you’re using the correct manage.py and that its using the right settings file. Let me know if none of that fixed it.
Posted by Damien on June 12, 2009 at 12:43 am
Hello,
I’m sorry for not replying here. But I’ve found the reason.
Watching your article, I thought the project name was management. So I was missing the appropriate directory structure.
Thanks
Posted by Jonathan on July 14, 2009 at 4:56 pm
Hi! first of all thanks for the info, you are so right about the lack of examples in that part, so thanks again.
I got a question, what if my command actually requires arguments?
example:
mycommand.py file1
what cass should i be using?
thanks beforehand
Posted by godavemon on July 14, 2009 at 5:25 pm
Great question. The B-List has a much more detailed tutorial on making custom commands.
http://www.b-list.org/weblog/2008/nov/14/management-commands/