Skip to main content
 首页 » 编程设计

python之属性错误 : 'module' object has no attribute 'Command'

2025年05月04日19虾米姐

我正在使用 django 1.7,我已经创建了这个管理命令:

文件结构:

app/ 
    __init__.py 
    management/ 
               __init__.py 
               commands/ 
                        __init__.py 
                        modal_asign.py 

代码:

from django.core.management.base import BaseCommand, CommandError 
from webinar.models import Webinar 
 
class Commands(BaseCommand): 
 
    help = 'Assign modal link to every webinar' 
 
    def handle(self): 
        latest_webinar = Webinar.objects.all().order_by('-webinar_date')[0] 
        for webinars in latest_webinar: 
            print "http://webinar.academiaa2.com/webinars/#displayModal" + webinars 

我在尝试使用 python manage.py modal_asign

进行测试时遇到此错误
Traceback (most recent call last): 
  File "manage.py", line 10, in <module> 
    execute_from_command_line(sys.argv) 
  File "/home/rafael/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 385, in execute_from_command_line 
    utility.execute() 
  File "/home/rafael/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 377, in execute 
    self.fetch_command(subcommand).run_from_argv(self.argv) 
  File "/home/rafael/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 238, in fetch_command 
    klass = load_command_class(app_name, subcommand) 
  File "/home/rafael/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 42, in load_command_class 
    return module.Command() 
AttributeError: 'module' object has no attribute 'Command' 

请您参考如下方法:

您的类名叫做Commands,而django 期望它叫做Command。因此错误。

改变

class Commands(BaseCommand): 

到

class Command(BaseCommand):