我在这里尝试做的是将变量result
传递给模板。我的问题是我需要将变量path
作为参数传递给tumor_classification()
函数,以获得result
的值。 '路径的价值'是从save()
函数获得的,因为我覆盖了它。我尝试将变量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()
谢谢!
答案 0 :(得分:0)
如果path
是短时间内需要的东西,您可以将其存储在会话中。请参阅sessions manual以供参考。会话与当前登录用户相关联。
request.session.put('path', path)
request.session.get('path', default='something)
但是,如果用户将多次调用创建BrainImage
的视图,而不是会话中的路径值或将被覆盖(全局也是如此)
处理这种情况的最佳方法是将path
存储在数据库中,例如存储在BrainImage
中。通过这种方式,您可以在线程安全,多用户安全的其他视图中检索它,以及更为重要的持久方式。
答案 1 :(得分:0)
通常是通过覆盖视图中的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