Skip to content

Django 基本教學 - 從無到有 Django-Beginners-Guide 📝

License

Notifications You must be signed in to change notification settings

twtrubiks/django-tutorial

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

django-custom-management-commands-tutorial

這邊紀錄如何客製化 management commands

教學

將這個 management commands 放到 musics 資料夾底下,

資料夾結構如下

musics/
    __init__.py
    models.py
    management/
        __init__.py
        commands/
            __init__.py
            welcome.py
    tests.py
    views.py

然後記得一定要將 musics 加入到 INSTALLED_APPS 底下,

否則 django 不會偵測.

INSTALLED_APPS = [
    ......
    "musics",
]

welcome.py 程式碼如下,

from django.core.management.base import BaseCommand

class Command(BaseCommand):

    # python3 manage.py help welcome

    help = 'hello django custom management commands'

    def add_arguments(self, parser):
        # Positional arguments
        parser.add_argument("name", type=str)

    def handle(self, *args, **kwargs):
        msg = f'handle - hello django custom management commands: {kwargs["name"]}'
        self.stdout.write(self.style.SUCCESS("success"))
        self.stdout.write(msg)

使用方法也很簡單, 先來測試一下是否有正確載入,

如果有出現 welcome 代表成功,

❯ python3 manage.py help

[musics]
    welcome

接著來測試一下指令

❯ python3 manage.py welcome test
success
handle - hello django custom management commands: test

如果你想 透過 vscode debug django custom management commands,

可參考 設定 Django Shell 中斷點.

如果想定期執行, 可以搭配 Linux 指令教學-Crontab 來執行定期需要執行的內容.

執行環境

  • Python 3.9

Reference

Donation

文章都是我自己研究內化後原創,如果有幫助到您,也想鼓勵我的話,歡迎請我喝一杯咖啡:laughing:

alt tag

贊助者付款

License

MIT license

About

Django 基本教學 - 從無到有 Django-Beginners-Guide 📝

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published