如何在Django中将图像传递给模板? [英] How can I pass an image to a template in Django?

查看:62
本文介绍了如何在Django中将图像传递给模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose that the corresponding function in views.py looks like

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 ?

How can I then display base_image in the get_img.html template?

推荐答案

您应该处理该图像,将其保存在本地磁盘上,然后向其发送路径,或者更像是将与该图像相对应的媒体URL作为上下文,html模板.您需要将django服务器配置为提供静态文件和媒体文件,并在生产环境中配置为这些文件提供服务.在此处阅读更多信息 https://docs.djangoproject.com/zh-CN/1.9/howto/static-files/

You should process the image, save it on local disk and then send a path to it or more like the media url which will correspond to that image as context to html template. You need to configure your django server to serve static and media files to do that and configure serving those files in production environment as well. Read more here https://docs.djangoproject.com/en/1.9/howto/static-files/

但是,如果您不能或真的不想将其保存在本地,则应该可以创建动态图像并与django一起使用PIL进行投放.就像在您应该添加的代码中一样.

However it should be possible to create dynamic image and serve with django in the fly with PIL if you can't or really do not want to save it locally. It will be sth like at the and of you code you should add.

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

还检查更多信息 http://effbot.org/zone/django-pil.htm ,虽然我没有测试它,但它可能会起作用.

Check also more info http://effbot.org/zone/django-pil.htm, it may work, although I didn't test it.

这篇关于如何在Django中将图像传递给模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆