简体   繁体   English

Django将变量作为参数传递给视图中的函数

[英]Django passing variable as a parameter to a function in a view

What I'm trying to do here is to pass the variable result to a template. 我在这里试图将变量result传递给模板。 My problem is that I need to pass the variable path as a parameter to the tumor_classification() function in order to get the value of result . 我的问题是,我需要将可变path作为参数传递给tumor_classification()函数,以便获得result的值。 The value of the 'path' is obtained from the save() function, as I overrode it. 当我覆盖它时,可以从save()函数获取“路径”的值。 I tried to make the variable path as global, but it doesn't work (the 'path' remains null). 我试图将变量path为全局path ,但是它不起作用(“路径”保持为空)。 How can I do this ? 我怎样才能做到这一点 ? The following code shows my views.py file : 以下代码显示了我的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()

Thank you ! 谢谢 !

If path is something which is required for a short period of time, you can store it in session. 如果path在短时间内是必需的,则可以将其存储在会话中。 See sessions manual for reference. 请参阅会议手册以供参考。 Session is something associated to currently logged in user. 会话是与当前登录用户相关联的东西。

request.session.put('path', path)

request.session.get('path', default='something)

However if user will call the view which creates BrainImage multiple times, than the path value in session or will be overwriten (the same happens with global) 但是,如果用户多次调用创建BrainImage的视图,则会话中的路径值将被覆盖或将被覆盖(对于全局变量,情况也是如此)

The best way to handle that is to store the path in database, for example in your BrainImage . 处理该问题的最佳方法是将path存储在数据库中,例如在BrainImage This way you can retrieve it in other views in a thread-safe, multisuser-safe and what's even more important persitent way. 这样,您就可以在其他视图中以线程安全,多用户安全以及更重要的持久性方式来检索它。

usually that is done by overriding the get_context_data method in your view, so: 通常,这是通过覆盖视图中的get_context_data方法来完成的,因此:

def get_context_data(self, **kwargs):
    context = super(BrainImageIndexView, self).get_context_data(**kwargs)
    context["result"] = self.something()
    return context

but what you want seems to be something a little different, you should move that def tumor_classification(image_address): in your model definition, change the signature to pick up the image address from the object itself and not as a parameter, and then in the template do something like 但是您想要的似乎有点不同,您应该移动def tumor_classification(image_address):在模型定义中,更改签名以从对象本身而不是参数中获取图像地址,然后在模板做类似的事情

 {% for img in images %}
      {{ img.get_tumor_classification }}
 {% endfor %}

example of the method in the model: 模型中方法的示例:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM