if multiple django apps define the same custom management command, which is used?

  • Last Update :
  • Techknowledgy :

A management command which takes one or more installed application labels as arguments, and does something with each of them.,A management command which takes one or more arbitrary arguments (labels) on the command line, and does something with each of them.,Rather than implementing handle(), subclasses must implement handle_app_config(), which will be called once for each application.,Rather than implementing handle(), subclasses must implement handle_label(), which will be called once for each label.

polls /
   __init__.py
models.py
management /
   __init__.py
commands /
   __init__.py
_private.py
closepoll.py
tests.py
views.py
from django.core.management.base
import BaseCommand, CommandError
from polls.models
import Question as Poll

class Command(BaseCommand):
   help = 'Closes the specified poll for voting'

def add_arguments(self, parser):
   parser.add_argument('poll_ids', nargs = '+', type = int)

def handle(self, * args, ** options):
   for poll_id in options['poll_ids']:
   try:
   poll = Poll.objects.get(pk = poll_id)
except Poll.DoesNotExist:
   raise CommandError('Poll "%s" does not exist' % poll_id)

poll.opened = False
poll.save()

self.stdout.write(self.style.SUCCESS('Successfully closed poll "%s"' % poll_id))
self.stdout.write("Unterminated line", ending = '')
class Command(BaseCommand):
   def add_arguments(self, parser):
   # Positional arguments
parser.add_argument('poll_ids', nargs = '+', type = int)

# Named(optional) arguments
parser.add_argument(
   '--delete',
   action = 'store_true',
   help = 'Delete poll instead of closing it',
)

def handle(self, * args, ** options):
   #...
   if options['delete']:
   poll.delete()
#...
from django.core.management.base
import BaseCommand, no_translations

class Command(BaseCommand):
   ...

   @no_translations
def handle(self, * args, ** options):
   ...
self.stdout.write(self.style.SUCCESS('...'))

Suggestion : 2

Last Updated : 06 Aug, 2021,GATE CS 2021 Syllabus

Step 1: Initialize a project by following command

django - admin startproject geeks_site

Step 2: Create an app named blog

python manage.py startapp blog

Step 6: Now, To migrate all your changes and start the server, run the following commands in your terminal

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

1) help: It tells what actually the command does. Run the following command and see the help

python manage.py stats--help

Now, Run the following command in your terminal :

python manage.py stats

Suggestion : 3

Aug 27, 2018

python manage.py help
Type 'manage.py help <subcommand>' for help on a specific subcommand.

   Available subcommands:

   [auth]
   changepassword
   createsuperuser

   [contenttypes]
   remove_stale_contenttypes

   [django]
   check
   compilemessages
   createcachetable
   dbshell
   diffsettings
   dumpdata
   flush
   inspectdb
   loaddata
   makemessages
   makemigrations
   migrate
   sendtestemail
   shell
   showmigrations
   sqlflush
   sqlmigrate
   sqlsequencereset
   squashmigrations
   startapp
   startproject
   test
   testserver

   [sessions]
   clearsessions

   [staticfiles]
   collectstatic
   findstatic
   runserver
mysite / < --project directory |
   --core / < --app directory |
   | --management /
   |
   | + --commands /
   |
   | + --my_custom_command.py < --module where command is going to live |
   | --migrations /
   |
   | + --__init__.py |
   | --__init__.py |
   | --admin.py |
   | --apps.py |
   | --models.py |
   | --tests.py |
   + --views.py |
   --mysite /
   |
   | --__init__.py |
   | --settings.py |
   | --urls.py |
   | --wsgi.py +
   --manage.py
python manage.py my_custom_command
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 now %s" % time)
python manage.py what_time_is_it

Suggestion : 4

Django management commands are included as part of Django apps and are designed to fulfill repetitive or complex tasks through a one keyword command line instruction. Every Django management command is backed by a script that contains the step-by-step Python logic to fulfill its duties. So when you type python manage.py runserver, behind the scenes Django triggers a much more complex Python routine.,What I'll do next is describe how to create custom management commands in your Django apps, so you can simplify the execution of routine or complex tasks through a single instruction.,Although standard Python try/except blocks work as expected inside Django management tasks, there are two syntax particularities you need to be aware of when creating Django management tasks: outputting messages and error handling.,I'll describe the purpose of Django management commands associated with core or third party Django apps as they come up in the book, just as I've done up to this point (e.g. static file management commands in static file topics, model management commands in model topics).

Listing 5-33. Django management command class with no arguments

from django.core.management.base
import BaseCommand, CommandError
from django.conf
import settings

class Command(BaseCommand):
   help = 'Send test emails'

def handle(self, * args, ** options):
   for admin_name, email in settings.ADMINS:
   try:
   self.stdout.write(self.style.WARNING("About to send email to %s" % (email)))
# Logic to send email here
# Any other Python logic can also go here
self.stdout.write(self.style.SUCCESS('Successfully sent email to "%s"' % email))
raise Exception
except Exception:
   raise CommandError('Failed to send test email')

Listing 5-34. Django management task class with arguments

from django.core.management.base
import BaseCommand, CommandError
from django.conf
import settings

class Command(BaseCommand):
   help = 'Clean up stores'

def add_arguments(self, parser):
   # Positional arguments are standalone name
parser.add_argument('store_id')

# Named(optional) arguments start with--
parser.add_argument(
   '--delete',
   default = False,
   help = 'Delete store instead of cleaning it up',
)
def handle(self, * args, ** options):
   # Access arguments inside ** options dictionary #options = {
      'store_id': '1',
      'settings': None,
      'pythonpath': None,
      # 'verbosity': 1,
      'traceback': False,
      'no_color': False,
      'delete': False
   }

Listing 5-35. Django management task folder structure and location

+-<BASE_DIR_project_name>
   |
   +-manage.py
   |
   |
   +---+-<PROJECT_DIR_project_name>
      |
      +-__init__.py
      +-settings.py
      +-urls.py
      +-wsgi.py
      |
      +-about(app)-+
      | +-__init__.py
      | +-models.py
      | +-tests.py
      | +-views.py
      | +-management-+
      | +-__init__.py
      | +-commands-+
      | +-__init__.py
      | |
      | |
      | +-sendtestemails.py
      |
      +-stores(app)-+
      +-__init__.py
      +-models.py
      +-tests.py
      +-views.py
      +-management-+
      +-__init__.py
      +-commands-+
      +-__init__.py
      |
      |
      +-cleanupstores.py
      +-updatemenus.py

Suggestion : 5
def handle_app(self, app, ** options)
from django.core.management.base
import AppCommand

class Command(AppCommand):
   def handle_app(self, app, ** options):
   pass
from django.core.management.base
import AppCommand

class Command(AppCommand):
   help = "Creates a basic admin.py file for the given app name(s)."

args = "[appname ...]"

def handle_app(self, app, ** options):
   pass
from django.contrib
import admin
from weblog.models
import Entry, Link

class EntryAdmin(admin.ModelAdmin):
   pass

class LinkAdmin(admin.ModelAdmin):
   pass

admin.site.register(Entry, EntryAdmin)
admin.site.register(Link, LinkAdmin)
from django.core.management.base
import AppCommand

ADMIN_FILE_TEMPLATE = ""
"from django.contrib import admin
from {
   {
      app
   }
}
import {
   {
      models | join: ", "
   }
}

{
   %
   for model in models %
}
class {
   {
      model
   }
}
Admin(admin.ModelAdmin):
   pass

{
   % endfor %
}

{
   %
   for model in models %
}
admin.site.register({
      {
         model
      }
   }, {
      {
         model
      }
   }
   Admin) {
   % endfor %
}
""
"

class Command(AppCommand):
   help = "Creates a basic admin.py file for the given app name(s)."

args = "[appname ...]"

def handle_app(self, app, ** options):
   pass
def handle_app(self, app, ** options):
   from django
import template
from django.db.models
import get_models

models = get_models(app)

Suggestion : 6

Last updated October 18, 2021

At this stage, the app’s file tree will look similar to this:

some_app /
   __init__.py
models.py
management /
   commands /
   print_book_titles.py
tests.py
views.py

The following code snippet is for a short custom management command. View the Django documentation on Writing custom django-admin commands for guidance on more complex needs.

from django.core.management.base
import BaseCommand, CommandError
from some_app.models
import Book

class Command(BaseCommand):
   help = 'Prints all book titles in the database'

def handle(self):
   try:
   books = Book.objects.all()
for book in books:
   self.stdout.write(self.style.SUCCESS(book.title))
except FieldDoesNotExist:
   self.stdout.write(self.style.ERROR('Field "title" does not exist.'))
return

self.stdout.write(self.style.SUCCESS('Successfully printed all Book titles'))
return