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 に答える