Django管理命令: using LabelCommand

标签 django django-admin python-2.7 django-manage.py

我想随此管理命令一起传递参数。我从命令行运行此代码为

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()

最佳答案

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

from django.core.management.base import LabelCommand

然后你只需覆盖 handle_label命令。

关于Django管理命令: using LabelCommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10292716/

相关文章:

css - css 中的 django 变量 - 我可以使用模板吗

python - 如何将随机整数设置为 Django CharField 的默认值?

python - 如何使用时间字段将指标数据添加到 influxdb?

python - isinstance(datetime.datetime, DateTimeField.value) 对于 Django DateTimeField 始终返回 false

python - Django allauth 自定义登录表单不呈现自定义用户模型中的所有字段

django ForeignKey null = true

python - Django 。在管理员的弹出窗口中编辑模型表单

django - 错误 ```禁止 (403) CSRF 验证失败。尝试登录管理员时请求中止 .`` `

python - 如何在Python中绘制这个树形图案?

python - 040和40的区别