首页 > 解决方案 > 在Django的函数中传递模型的图像属性

问题描述

我有一个名为 的函数detectFace(input_file),其中输入文件是一个图像。我想通过views.py模板呈现结果,但找不到方法。图像将通过模板上传并在detectFace(input_file).

像这样的东西: -

def detectFace(input_file):
    """Operation on input_file
    """
    pass

现在views.py我正在尝试创建这样的东西

def face_recog(request):
    context = ??
    return render(request, 'templates/face.html', context)

我想知道那些问号。我应该如何进行?

标签: djangopython-3.xwebdjango-modelsface-recognition

解决方案


您可以通过访问访问上传的文件request.FILES['filename'],然后您可以将该文件传递给您的函数。就像是:

def detectFace(input_file):
    """Operation on input_file
    """
    # Some processing
    return something

def face_recog(request):
    input_file = request.FILES['image_file']
    some_data = detectFace(input_file) # call the function
    context = {'somekey': some_data} # data returned by detectFace() function.
    return render(request, 'templates/face.html', context)

在您的 HTML 中,表单应如下所示:

<form method="POST" enctype='multipart/form-data'>
    {% csrf_token %}
    <input type="file" name="image_file" />
    <input type="submit"></input>
    {{ form }}
</form>

推荐阅读