Write a custom django-admin command
You waste today, is the person who died yesterday expected tomorrow.Copy the code
The opening words:
Py
Key points of operation steps:
Step 1: Create a custom command module
In an existing project, under the project app you want to set, add the management/ Commands directory and create a Python module. The module name cannot start with “_”, otherwise the module will not be set as a custom command. The custom command is the name of the module. The created directory tree is as follows:
Py management/ commands/ _private.py # This module will not be added to the custom newtest.py # command This module will be set to a custom command named tests.py views.pyCopy the code
Note: The app for adding custom commands needs to be registered in 'settings.py' INSTALLED_APPS.Copy the code
Step 2: Write custom command functions
Set newtest.py to implement the function, newtest.py content:
import os import traceback from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): def add_arguments(self, parser): Parser. Add_argument (dest='appname', # type= STR, # help=' appname', # help) def handle(self, *args, **options): try: shell_info ='python manage.py test %s --keepdb --settings=appname.test_settings' % (options['appname']) Os.system (shell_info) self.stdout.write(self.style.success (' %s' % (__file__, options['appname'])) except: Self.stdout.write (traceback.format_exc()) self.stdout.write(self.style.error (' command execution ERROR '))Copy the code
When python manage.py newtest appname is executed, the test test is called and the specified test specific settings.py configuration is run.
Note: To print output, use 'self.stdout.write("Unterminated line", ending= ")'. The 'ending=' argument specifies the end of the output. `Copy the code
If you do not understand the place, you can leave a message reply.
This article started at BigYoung