2 回答

TA貢獻1783條經驗 獲得超4個贊
首先,您的views.py 在 POST 的情況下返回圖像。接下來的部分將告訴瀏覽器您返回的“頁面”實際上是一張圖像,并要求瀏覽器顯示該圖像。這就是為什么瀏覽器只顯示圖像。
response = HttpResponse(content_type='image/jpg') canvas = FigureCanvasAgg(fig) canvas.print_jpg(response) return response
因此,在這兩種情況下,您都應該返回呈現的模板。return render(request, 'gtdefault.html', context)
我了解您想在網頁中顯示圖像(gtdefault.html)?這意味著類似這樣的事情。
{% if submitted %} <img src="you need source here" /> {% else %}
現在,棘手的部分是將源 URL 放入上下文中。您可以將生成的圖像上傳到 django meda 文件或某些外部存儲(如 AWS S3)一段時間,然后使用從那里獲得的 url。
或者您可以按照以下方式傳遞頁面內的圖像:How to display picture from memory in Django?
在第一種方法中,如果圖像稍后會再次查看,則可以使用瀏覽器緩存。對于后一種情況,您可以忽略存儲,但實現起來“更繁瑣”。

TA貢獻1995條經驗 獲得超2個贊
我將views.py中的響應更改為render(request, 'gtdefault.html', context)。為了將圖像編碼為base64,我必須遍歷PIL的圖像,然后從PIL的圖像到base64。我還submitted從我的代碼中刪除并改為使用request.method == 'POST'. 再次感謝@Juho Rutila!
我確信可能有一種不那么迂回的方法來做到這一點,但這是我可以開始工作的第一種方法。
我修改后的views.py:
import io
import base64
from PIL import Image
def grapher_tool_input(request):
if request.method == 'POST':
form = GraphingInput(request.POST)
if form.is_valid():
cd = form.cleaned_data
fig = graph(cd['left_end'], cd['right_end'], cd['top'], cd['bottom'], cd['function'])
buf = io.BytesIO()
fig.savefig(buf, format='png')
im = Image.open(buf)
buf2 = io.BytesIO()
im.save(buf2, format='png')
im_str = base64.b64encode(buf2.getvalue()).decode()
data_uri = 'data:image/png;base64,'
data_uri += im_str
context = dict()
context['data'] = data_uri
return render(request, 'gtdefault.html', context)
else:
form = GraphingInput(initial={'left_end':-5, 'right_end':5, 'bottom':-5, 'top':5})
context ={
'form': form,
}
return render(request, 'gtdefault.html', context)
我修改后的gtdefault.html:
{% extends 'base.html' %}
{% block content %}
{% if request.method == 'POST' %}
<img src={{ data }} alt="" height="250" ,width="250">
{% else %}
<form action="" method="post" novalidate>
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Graph">
{% csrf_token %}
</form>
{% endif %}
{% endblock content %}
添加回答
舉報