假设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))
如何在base_image
模板中显示get_img.html
?
答案 0 :(得分:7)
您应该处理图像,将其保存在本地磁盘上,然后发送一个或更多的路径,例如媒体网址,它将与该图像对应,作为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,虽然我没有测试,但它可能会有效。
答案 1 :(得分:1)
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/'
添加用于存储manage.py的模板和媒体/图像目录。
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>
答案 2 :(得分:0)
I think you must save image (write it to temp file) in static directory of project and in template use static command and image file name to display it.