30
loading...
This website collects cookies to deliver better user experience
Thanks for reading! - Content provided by App Generator.
cmd_time.py
- show current timestampcmd_apps
- list all registered appscmd_models
- list all apps and associated modelscmd_showcfg
- list all CFG keys and valuesstartapp
subcommand:$ python manage.py startapp app_customcmd
app
directory, we need to create a directory structure as shown below:< PROJECT ROOT > <-- project directory
|
|-- app_customcmd/ <-- app directory
| |-- management/
| | +-- __init__.py
| | +-- commands/
| | +-- __init__.py
| | +-- cmd_....py <-- module where all commands are saved
commands
directory are automatically discovered even without an application restart. Configure Django to use the app
app_customcmd
in the project configuration:INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app_customcmd', # <-- NEW
]
app_customcmd/management/commands
directory:from django.core.management.base import BaseCommand
from django.utils import timezone
class Command(BaseCommand):
help = 'Displays current time'
def handle(self, *args, **kwargs):
time = timezone.now().strftime('%X')
self.stdout.write("It's %s" % time)
handle
method and the execution should display something similar to this:$ python manage.py cmd_time
It's 09:18:08 <-- The output from our custom CMD
BaseCommand
as a super-class for our definition. from django.core.management.base import BaseCommand
from django.apps import apps
class Command(BaseCommand):
help = 'Displays registered apps'
def handle(self, *args, **kwargs):
for app in apps.get_app_configs():
self.stdout.write(" APP -> %s" % app.verbose_name)
Script execution and output:
$ python manage.py cmd_apps
APP -> Administration # Default Django App
APP -> Authentication and Authorization # Default Django App
APP -> Content Types # Default Django App
APP -> Sessions # Default Django App
APP -> Messages # Default Django App
APP -> Static Files # Default Django App
APP -> App_Customcmd # <-- Our NEW App
from django.core.management.base import BaseCommand
from django.apps import apps
class Command(BaseCommand):
help = 'Displays registered apps and models'
def handle(self, *args, **kwargs):
# Iterate over apps
for app in apps.get_app_configs():
self.stdout.write(" APP -> %s" % app.verbose_name)
# Iterate over models # <-- New Code
for model in app.get_models(): # <-- New Code
self.stdout.write("\t |- (model) -> %s" % model) # <-- New Code
The execution and output
$ python manage.py cmd_models
APP -> Administration
|- (model) -> <class 'django.contrib.admin.models.LogEntry'>
APP -> Authentication and Authorization
|- (model) -> <class 'django.contrib.auth.models.Permission'>
|- (model) -> <class 'django.contrib.auth.models.Group'>
|- (model) -> <class 'django.contrib.auth.models.User'>
APP -> Content Types
|- (model) -> <class 'django.contrib.contenttypes.models.ContentType'>
APP -> Sessions
|- (model) -> <class 'django.contrib.sessions.models.Session'>
APP -> Messages
APP -> Static Files
APP -> App_Forms
APP -> App_Pdf
APP -> App_Customcmd
APP -> App
|- (model) -> <class 'app.models.Book'>
settings
object for proprieties and print all values.from django.core.management.base import BaseCommand
from django.utils import timezone
from django.conf import settings
class Command(BaseCommand):
help = 'Displays project config'
def handle(self, *args, **kwargs):
# type( settings ) => <class 'django.conf.LazySettings'>
# settings.__dict__
# Iterate over apps
for key in settings.__dict__.keys():
self.stdout.write(" Cfg Key: " + key + " -> %s" % settings.__dict__[ key ] )
The output and execution:
(env) PS D:\work\repo-samples\django-learn-by-coding> python manage.py cmd_showcfg
Cfg Key: _wrapped -> <Settings "config.settings">
Cfg Key: INSTALLED_APPS -> ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app_forms', 'app_pdf', 'app_customcmd', 'app']
Cfg Key: DEBUG -> True
Cfg Key: LOGGING_CONFIG -> logging.config.dictConfig
Cfg Key: LOGGING -> {}
Cfg Key: DEFAULT_EXCEPTION_REPORTER -> django.views.debug.ExceptionReporter
Cfg Key: FORCE_SCRIPT_NAME -> None
Cfg Key: DEFAULT_TABLESPACE ->
Cfg Key: DEFAULT_AUTO_FIELD -> django.db.models.BigAutoField
Cfg Key: ABSOLUTE_URL_OVERRIDES -> {}
Cfg Key: AUTH_USER_MODEL -> auth.User
Cfg Key: DATABASES -> {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': WindowsPath('D:/work/repo-samples/django-learn-by-coding/db.sqlite3'), 'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'OPTIONS': {}, 'TIME_ZONE': None, 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIGRATE': True, 'MIRROR': None, 'NAME': None}}}
...
(truncated output)
Thanks for reading! For more resources and support, feel free to access: