亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

嘗試在 django 視圖生成的網頁中顯示圖像

嘗試在 django 視圖生成的網頁中顯示圖像

子衿沉夜 2023-10-06 19:14:09
我的目標是有一個簡單的表單,允許用戶輸入一個函數來繪制圖形,以及一個顯示窗口,一旦用戶點擊提交按鈕,我希望 numpy 和 matplotlib 獲取表單數據并生成一個圖形,然后在新網頁中顯示該數字。到目前為止,我按照“創建聯系表單視圖”來生成表單并使數據可用。我發現這個可以讓我顯示圖像。然而,圖像就像這樣占據了整個瀏覽器窗口。我希望該圖像顯示在我的網頁中。我對 Django 很陌生,如果這沒有意義或信息不夠,我很抱歉。如果需要,我很樂意提供說明或其他信息。這是我的應用程序的views.py:from django.shortcuts import renderfrom django.http import HttpResponsefrom matplotlib.backends.backend_agg import FigureCanvasAggfrom .forms import GraphingInputfrom .graphing_tool import graphimport io# Create your views here.def grapher_tool_input(request):    submitted = False    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'])            response = HttpResponse(content_type='image/jpg')            canvas = FigureCanvasAgg(fig)            canvas.print_jpg(response)            return response    else:        form = GraphingInput(initial={'left_end':-10, 'right_end':10, 'bottom':-10, 'top':10})        if 'submitted' in request.GET:            submitted = True        context ={            'form': form,            'submitted': submitted,        }    return render(request, 'gtdefault.html', context)這是我的 forms.pyfrom django import formsclass GraphingInput(forms.Form):    left_end = forms.FloatField(max_value=10000000, min_value=-10000000, label='Left End Point')    right_end = forms.FloatField(max_value=10000000, min_value=-10000000, label='Right End Point')    bottom = forms.FloatField(max_value=10000000, min_value=-10000000, label='Bottom of Window')    top = forms.FloatField(max_value=10000000, min_value=-10000000, label='Top of Window')    function = forms.CharField(min_length=1, label='f(x)')
查看完整描述

2 回答

?
慕娘9325324

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?

在第一種方法中,如果圖像稍后會再次查看,則可以使用瀏覽器緩存。對于后一種情況,您可以忽略存儲,但實現起來“更繁瑣”。


查看完整回答
反對 回復 2023-10-06
?
拉風的咖菲貓

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 %}


查看完整回答
反對 回復 2023-10-06
  • 2 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號