Django - 使用视图中的参数调用命令行



我正在尝试调用从视图更改数据库的命令。基本上,一旦加载了视图,参数就会更改。如果我从终端运行命令,它可以工作,但是如果我尝试从视图中调用它,我会不断收到此错误。
我相信我传递字典的方式存在错误,因为该命令在终端工作正常。也可能是因为我正在尝试更新当前向用户显示的模型,但我也尝试传递不同的 ID 作为参数,并且会引发相同的错误。

CommandError at /sample/45/
Error: argument num: invalid int value: "{'num': 45}"
Request Method:     GET
Request URL:    http://127.0.0.1:8000/sample/45/
Django Version:     2.0
Exception Type:     CommandError
Exception Value:    
Error: argument num: invalid int value: "{'num': 45}"
Exception Location:     /usr/local/lib/python3.6/dist-packages/django/core/management/base.py in error, line 60
Python Executable:  /usr/bin/python3
Python Version:     3.6.5
Python Path:    
['/home/ander/Desktop/Proyecto/meduloblastoma/Code/MedulloblastomaProject',
'/usr/lib/python36.zip',
'/usr/lib/python3.6',
'/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages',
'/usr/lib/python3/dist-packages',
'/home/ander/Desktop/Proyecto/meduloblastoma/Code/MedulloblastomaProject']
Server time:    Mon, 4 Jun 2018 18:35:37 +0200

这是我使用的代码。

classify.py

from django.core.management.base import BaseCommand
from rpy2.robjects.packages import importr
import rpy2.robjects as ro
from sample.models import Sample
class Command(BaseCommand):
"""
Management command to run the classifier
"""
def add_arguments(self, parser):
parser.add_argument('num',type=int)
help="Runs the classifier on uploaded samples"
def handle(self,*Args,**Options):
num=Options['num']
samples=Sample.objects.filter(id=num)
print(samples)
for sample in samples:
if sample.classificator=="Not classified":
sample.classificator="Classified"

views.py

@login_required
def detail_sample(request, id):
instance = get_object_or_404(Sample, id=id)
call_command('classify', {'num': instance.id})
if instance.user == request.user:
if instance.allow:
agreed="This data is allowed to be used for improvement of the algorithm"
else:
agreed="This data is NOT allowed to be used for improvement of the algorithm"
context={
"title": instance.title,
"user":instance.user.username,
"comment": instance.comment,
"time": instance.time,
"diagnosis": instance.diagnosis,
"gender": instance.gender,
"file1": instance.file1,
"file2":instance.file2,
"id": instance.id,
"a":instance.classificator, #a[0][2:],
"b":instance.classificator, #a[1][0],
"agree":agreed,
"allow":instance.save,
}
return render(request, "sample/sample_detail.html", context)
else:
raise Http404

你应该num作为关键字参数传递:

call_command('classify', num=instance.id)

但是,最好将代码分解到单独的方法中。

def classify(num):
samples=Sample.objects.filter(id=num)
for sample in samples:
if sample.classificator=="Not classified":
sample.classificator="Classified"

那么你的管理命令和视图都可以调用classify(num),而不必使用call_command

相关内容

最新更新