如何将图像传递给 Django 中的模板?

How can I pass an image to a template in Django?

假设views.py中对应的函数看起来像

from PIL import Image
def get_img(request, img_source)
    base_image = Image.open(os.getcwd() + '/deskprod/media/img/'+ img_source + ".png")
    #Some editing of base_image done with PIL that prevents image from being directly loaded in html
    return render_to_response('get_img.html', {
        'base_image': base_image},
        context_instance=RequestContext(request))

然后如何在 get_img.html 模板中显示 base_image

我认为你必须在项目的静态目录中保存图像(将其写入临时文件),并在模板中使用静态命令和图像文件名来显示它。

您应该处理图像,将其保存在本地磁盘上,然后发送路径或更像媒体 url,它将对应于该图像作为 html 模板的上下文。您需要配置您的 django 服务器以提供静态和媒体文件来执行此操作,并配置在生产环境中提供这些文件。在这里阅读更多 https://docs.djangoproject.com/en/1.9/howto/static-files/

然而,如果您不能或真的不想在本地保存它,应该可以创建动态图像并使用 PIL 与 django 一起使用。就像您应该添加的代码一样。

response = HttpResponse(mimetype="image/png")
base_image.save(response, "PNG")
return response

另请查看更多信息http://effbot.org/zone/django-pil.htm,它可能会起作用,尽管我没有测试它。

settings.py

   'DIRS': [os.path.join(BASE_DIR, 'templates')], # add this line in TEMPLATES
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media/images')
    MEDIA_URL = '/media/images/'

add templates and media/images directory where manage.py is stored.

urls.py

urlpatterns = [

                  url('polls/', views.get_img, name="polls"),


              ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views.py

from django.conf import settings

def get_img(request):
    path = settings.MEDIA_ROOT
    img_list = os.listdir(path + "/")
    print(img_list[0])
    base_image = "http://127.0.0.1:8000/media/images/" + img_list[0]
    content = {"base_image": base_image}
    return render(request, 'get_img.html', content)

get_img.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>drop_down</title>
</head>
<body>

  {{base_image}}
  <img src="{{base_image}}" style="width: 20%; height: 20%;" alt="{{base_image}}">

</body>
</html>