python - 从 django 自定义命令请求输入?

标签 python django

我在 django 中创建了一个自定义命令来删除 CMD 中的一个设置帐户,但我希望能够运行 python 文件并让命令行询问我要删除的帐号然后将其删除。这是我目前所拥有的。

from django.core.management.base import BaseCommand, CommandError
from accounts.models import client

class Command(BaseCommand):

    args = '<client_id client_id ...>'
    help = 'Closes the specified account.'

    def handle(self, *args, **options):
        for client_id in args:
            try:
                x = client.objects.get(pk=int(client_id))
            except client.DoesNotExist:
                raise CommandError('Client "%s" does no exist' % client_id)

            x.delete()

            self.stdout.write('Successfully closed account "%s"' % client_id)

最佳答案

使用内置的 raw_input()功能:

def handle(self, *args, **options):
    if args:
        ids = args
    else:
        ids = raw_input('Enter comma-delimited list of ids: ').split(',')
    for client_id in ids:
        ...

编辑:在 Python3 中,使用 input()而不是 raw_input()

关于python - 从 django 自定义命令请求输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28301039/

相关文章:

Django "lazy query execution"原理

django - 在 django 中与 cassandra 交互?

python - 在共享主机上设置 Django 网站

django - 从 DetailView 获取 pk 以进行 lte/gte 比较 (Django)

python - Django:DeleteView 将外键模型中的参数传递给 get_success_url

python - 使用 XML-RPC WordPress API 和 Python 发布带有类别的帖子

python - 在golang中Flask的@before_first_request相当于什么?

python - 所有输入提醒程序的时间都以秒计

python - 如何通过 BS4 获取维基百科页面的维基数据项的 Q 编号?

python - 套接字接收不返回