Django:在模板中嵌入图像

时间:2018-06-13 11:43:14

标签: django django-templates django-views

我需要在我的网页中显示图片。图像存储在views.py。

中的变量中

以下大多数解决方案都使用HttpResponse输出图像,但我希望将图像嵌入到我的html模板中。

from django.http import HttpResponse

def my_image(request):
    image_data = open("/path/to/my/image.png", "rb").read()

PS。我通过使用matplotlib来创建图像来获取图像。所以我不能使用静态文件夹。下面给出的示例代码(信用:this

import sys
from django.http import HttpResponse
import matplotlib as mpl
mpl.use('Agg') # Required to redirect locally
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import rand
try:
    # Python 2
    import cStringIO
except ImportError:
    # Python 3
    import io

def get_image(request):
   """
   This is an example script from the Matplotlib website, just to show 
   a working sample >>>
   """
   N = 50
   x = np.random.rand(N)
   y = np.random.rand(N)
   colors = np.random.rand(N)
   area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses
   plt.scatter(x, y, s=area, c=colors, alpha=0.5)
   """
   Now the redirect into the cStringIO or BytesIO object >>>
   """
   if cStringIO in sys.modules:
      f = cStringIO.StringIO()   # Python 2
   else:
      f = io.BytesIO()           # Python 3
   plt.savefig(f, format="png", facecolor=(0.95,0.95,0.95))
   plt.clf()
   """
   Add the contents of the StringIO or BytesIO object to the response, matching the
   mime type with the plot format (in this case, PNG) and return >>>
   """
   return HttpResponse(f.getvalue(), content_type="image/png")
        return HttpResponse(image_data, content_type="image/png")

1 个答案:

答案 0 :(得分:0)

将图像保存在媒体目录中,然后使用ajax更新div

类似

def get_image(request):
   """
   This is an example script from the Matplotlib website, just to show 
   a working sample >>>
   """
   N = 50
   x = np.random.rand(N)
   y = np.random.rand(N)
   colors = np.random.rand(N)
   area = np.pi * (15 * np.random.rand(N))**2 # 0 to 15 point radiuses
   plt.scatter(x, y, s=area, c=colors, alpha=0.5)
   filepath = os.path.join(settings.MEDIA_PATH,'/name_of_the_file.png')
   plt.savefig(filepath, facecolor=(0.95,0.95,0.95))
   plt.clf()
   return HttpResponse(filepath)

然后使用ajax请求进入功能

 $.ajax({       type: "POST",
                url: 'THE URL TO THE FUNCTION',
                data: {
                    csrfmiddlewaretoken:  $('[name="csrfmiddlewaretoken"]').val(),

                },
                 success: function(response){
                    $('#your_div_id').html("<img src=\""+responce+"\"></img>")
                  }
            });
相关问题