[英]Django passing variable as a parameter to a function in a view
我在这里试图将变量result
传递给模板。 我的问题是,我需要将可变path
作为参数传递给tumor_classification()
函数,以便获得result
的值。 当我覆盖它时,可以从save()
函数获取“路径”的值。 我试图将变量path
为全局path
,但是它不起作用(“路径”保持为空)。 我怎样才能做到这一点 ? 以下代码显示了我的views.py
文件:
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views.generic import FormView, DetailView, ListView
from django.conf import settings
import os
from .forms import BrainImageForm
from .models import BrainImage
from .brain import *
global result
class BrainImageView(FormView):
template_name = 'brain_image_form.html'
form_class = BrainImageForm
def form_valid(self, form):
brain_image = BrainImage(
image = self.get_form_kwargs().get('files')['image']
)
brain_image.save()
global path
path = brain_image.save() # this is the variable I need to pass to the function tumor_classification() below
self.id = brain_image.id
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
return reverse('brain_image',kwargs = {'pk': self.id})
class BrainImageIndexView(ListView):
model = BrainImage
template_name = 'brain_image_view.html'
context_object_name = 'images'
def tumor_classification(image_address):
path = settings.MEDIA_ROOT+'/'+image_address
img = selectImage(path)
segmented = segmentation(img)
replaced = replace(img, segmented)
extractFeatures(replaced)
classif = createSVMClassifier(settings.BASE_DIR+'/main/datasets/input_features.csv', settings.BASE_DIR+'/main/datasets/benign_input_features.csv')
result = classify(classif, "tumor_features.csv")
return result
result = tumor_classification(path) # this is where I need to pass the 'path' variable
queryset = BrainImage.objects.all()
谢谢 !
如果path
在短时间内是必需的,则可以将其存储在会话中。 请参阅会议手册以供参考。 会话是与当前登录用户相关联的东西。
request.session.put('path', path)
request.session.get('path', default='something)
但是,如果用户多次调用创建BrainImage
的视图,则会话中的路径值将被覆盖或将被覆盖(对于全局变量,情况也是如此)
处理该问题的最佳方法是将path
存储在数据库中,例如在BrainImage
。 这样,您就可以在其他视图中以线程安全,多用户安全以及更重要的持久性方式来检索它。
通常,这是通过覆盖视图中的get_context_data方法来完成的,因此:
def get_context_data(self, **kwargs):
context = super(BrainImageIndexView, self).get_context_data(**kwargs)
context["result"] = self.something()
return context
但是您想要的似乎有点不同,您应该移动def tumor_classification(image_address):
在模型定义中,更改签名以从对象本身而不是参数中获取图像地址,然后在模板做类似的事情
{% for img in images %}
{{ img.get_tumor_classification }}
{% endfor %}
模型中方法的示例:
class BrainImage(models.Model):
....
def tumor_classification(self):
image_address = self.image.path
path = settings.MEDIA_ROOT+'/'+image_address
img = selectImage(path)
segmented = segmentation(img)
replaced = replace(img, segmented)
extractFeatures(replaced)
classif = createSVMClassifier(settings.BASE_DIR+'/main/datasets/input_features.csv', settings.BASE_DIR+'/main/datasets/benign_input_features.csv')
result = classify(classif, "tumor_features.csv")
return result
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.