2

我想与这个管理命令一起传递参数。我从命令行运行此代码

python manage.py example1 amita

其中 example1 是我的文件名, amita 是参数。在运行这个我得到错误。我正在粘贴回溯:

Traceback (most recent call last):


File "manage.py", line 79, in <module>
    execute_manager(settings)
  File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 438, in execute_manager
    utility.execute()
  File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 379, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 261, in fetch_command
    klass = load_command_class(app_name, subcommand)
  File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 68, in load_command_class
    return module.Command()
AttributeError: 'module' object has no attribute 'Command'

example1.py 的代码如下

from django.core.management.base import LabelCommand
from django.core.management.base import BaseCommand


def hello(name):
  print name

def hello1(name):
  print name


class LabelCommand(BaseCommand):
    """
    A management command which takes one or more arbitrary arguments
    (labels) on the command line, and does something with each of
    them.

    Rather than implementing ``handle()``, subclasses must implement
    ``handle_label()``, which will be called once for each label.

    If the arguments should be names of installed applications, use
    ``AppCommand`` instead.

    """
    args = '<label label ...>'
    label = 'label'

    def handle(self, *labels, **options):
        if not labels:
            raise CommandError('Enter at least one %s.' % self.label)

    output = []
    for label in labels:
        label_output = self.handle_label(label, **options)
        if label_output:
            output.append(label_output)
    return '\n'.join(output)



    def handle_label(self, label, **options):
        """
        Perform the command's actions for ``label``, which will be the
        string as given on the command line.

        """
        hello(label)
        hello1(label)
        raise NotImplementedError()
4

1 回答 1

2

Django 已经有一个你应该使用的 LabelCommand 类:

from django.core.management.base import LabelCommand

然后你只需要覆盖handle_label命令。

于 2013-01-04T14:08:40.517 回答