How to Create Custom Django Management Commands

Blog
Spread the love

Django comes with a variety of command line utilities that can be either invoked using django-admin.py or the convenient manage.py script.

We can also add our own commands. Those management commands can be very handy when you need to interact with your application via command line using a terminal and it can also serve as an interface to execute cron jobs.

Introduction:

You are probably already familiar with commands like

python manage.py startapp

  • python manage.py startproject
  • python manage.py makemigrations
  • python manage.py migrate
  • python manage.py runserver
  • python manage.py collectstatic

To see a complete list of commands you can run the command below:

python manage.py help

We can create our own commands for our apps and include them in the list by creating a management/commands directory inside an app directory, like below:

The name of the command file will be used to invoke using the command line utility.

For example, if our command was called my_custom_command.py , then we will be able to execute it via:

python manage.py my_custom_command

Basic Example

A basic example of what the custom command should look like:

management/commands/current_time.py

Styling:

We can improve the output by setting an appropriate color to the output message.
self.stdout.write(self.style.SUCCESS(”It’s now %s” % time))

Basically a Django management command is composed by a class named command which inherits from BaseCommand.

The command code should be defined inside the handle() method.

See how we named our module current_time.py.

This command can be executed as:

python manage.py current_time

Output:

It’s now 06:35:31

bluethinkinc_blog

bluethinkinc_blog

2023-09-19

0

Leave a Reply

Your email address will not be published. Required fields are marked *

Find More Blogs

Enhancing Productivity with Dynamics 365: The Power of Session Restore

Spread the love Enhancing Productivity with Dynamics 365:

Salesforce Admin

Spread the love In our last blog, we discussed common

Unlocking AI with Spring Boot: Real-World Use Cases and Solutions

Spread the love Artificial Intelligence (AI) has moved from

Enhancing Performance with Reactive Java: A Beginner-Friendly Guide

Spread the love In today’s fast-paced software

Integrating Azure Function with Dynamics 365

Spread the love Signup on azure portal and make sure to

How to Create a Power Apps Component Framework (PCF) with React

Spread the love If youʼve been looking to supercharge your

Customize lead qualification for a seamless experience

Spread the love When the 2024 Release Wave 2 was launched,

Create a Custom Console Command in Spryker

Spread the love In Spryker, developers can create custom

SALESFORCE

Spread the love Salesforce is a cloud-based software

CRUD Operation in Spryker Backoffice with a Custom Module

Spread the love Spryker is a highly flexible and modular

bluethinkinc Blogs