2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Djangoでカスタムコマンドを作成する

Last updated at Posted at 2024-07-18

はじめに

こんにちは、Python初心者のkeitaMaxです。

今回はDjangoでカスタムコマンドを作成してみようと思います。

前回の記事はこちら。

作業するディレクトリ作成からブラウザに文字列を表示する

以下コマンドでbatchディレクトリを作成します。

python3 manage.py startapp batch

これをするとbatchディレクトリが作成されます。

フォルダを以下のように修正、追加します。

app/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path("batch/", include("batch.urls")),
]
batch/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path("", views.index, name="index"),
]

batch/views.py
from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

このように修正した後、以下のURLにアクセスすると設定した文字列が出てくるはずです。

http://localhost:8000/batch/

スクリーンショット 2024-07-18 19.27.31.png

コマンドの作成

以下のようにディレクトリとファイルを作成します。

batch
└── management
    ├── __init__.py
    └── commands
        ├── __init__.py
        └── example.py
example.py
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = "Help message"

    def handle(self, *args, **options):
        print("Hello, World!")

__init__.pyファイルは空のままで大丈夫です。

また、settings.pyに以下を追加します。

settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'batch',  // 追加
]

これでコマンド作成が完了です。

あとは以下コマンドでコンテナの中に入り、

docker compose exec app bash

以下コマンドで今作成したコマンドを実行してみましょう。

python manage.py example
root@ada83e062183:/code# python3 manage.py example
Hello, World!
root@ada83e062183:/code# python3 manage.py example

Hello, World!とでてくれば完了です。

おわりに

この記事での質問や、間違っている、もっといい方法があるといったご意見などありましたらご指摘していただけると幸いです。

最後まで読んでいただきありがとうございました!

参考

次の記事

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?