You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django自定义管理命令调用提示Unknown command,请求排查配置问题

问题排查:调用Django自定义命令提示"Unknown command"

项目结构

app/
├─ management/
│  ├─ commands/
│  │  ├─ customcommand.py
myfunction.py
site/
├─ settings.py

settings.py 内容

"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 4.1.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path
from dotenv import load_dotenv

load_dotenv()

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '****'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app'
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'site.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'site.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Kolkata'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

REST_FRAMEWORK = {
  'DEFAULT_PERMISSION_CLASSES': [
    'rest_framework.permissions.AllowAny'
  ]
}

customcommand.py 内容

from django.core.management.base import BaseCommand, CommandError
import time
import requests

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

    def handle(self, *args, **options):
        print("execued the commands success!!")
        start_time = time.time()

        for number in range(1, 50):
            url = f'https://pokeapi.co/api/v2/pokemon/{number}'
            resp = requests.get(url)
            pokemon = resp.json()
            print(pokemon['name'])

        print("--- %s seconds ---" % (time.time() - start_time))

myfunction.py 原始内容

from django.core import management

def funcA():
    management.call_command('customcommand')

funcA()

问题现象

直接运行myfunction.py时,抛出错误:

raise CommandError("Unknown command: %r" % command_name)

已尝试添加os.environ['DJANGO_SETTINGS_MODULE'] = 'site.settings',但问题仍未解决。

解决方案

1. 完整初始化Django环境

仅设置环境变量不足以让Django加载应用和命令,必须调用django.setup()完成初始化。修改后的myfunction.py如下:

import os
import django
from django.core import management

# 设置Django配置模块
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'site.settings')
# 初始化Django
django.setup()

def funcA():
    management.call_command('customcommand')

funcA()

2. 检查目录结构中的__init__.py文件

Django需要识别management和commands为Python包,因此这两个目录下必须存在空的__init__.py文件。补全后的项目结构应为:

app/
├─ management/
│  ├─ __init__.py
│  ├─ commands/
│  │  ├─ __init__.py
│  │  ├─ customcommand.py
myfunction.py
site/
├─ settings.py

3. 确认应用已正确注册

检查settings.py中的INSTALLED_APPS是否包含'app',你的配置中已经添加,这一步没问题,但如果后续修改应用名称需要同步更新。

内容的提问来源于stack exchange,提问作者devil coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 07:35:22