簡體   English   中英

Highcharts 圖表未顯示在 Django 模板 html 中

[英]Highcharts graph not displaying in Django template html

我正在使用 Django/python/sqlite3 制作網站。 我還使用 ebay-python-sdk 查詢 ebay 數據庫並根據關鍵字獲取信息。 我試圖將時間戳轉換為毫秒並將這些值傳遞到 Highcharts x 軸,並將該項目的最終售價傳遞到 y 軸。 該圖未顯示在 Django 模板(稱為“graphs.html”)中。 我的代碼如下:

display_graphs/views.py

from django.shortcuts import render
from ebaysdk.finding import Connection as finding
import xmltodict
from json import loads, dumps
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import io
from matplotlib.backends.backend_agg import FigureCanvasAgg
from django.http import HttpResponse

content_df = pd.DataFrame()

def display_the_graphs(request):
    keywords = request.POST.get('search')
    api = finding(appid='JohnHein-homepage-PRD-392e94856-07aba7fe', config_file=None, siteid='EBAY-US')
    api_request = {'keywords':keywords, 'itemFilter':[{'name':'SoldItemsOnly', 'value':True},]}
    response = api.execute('findCompletedItems', api_request)
    content = response.content
    xml_dict = xmltodict.parse(content)
    content_dict = to_dict(xml_dict)
    count = content_dict['findCompletedItemsResponse']['searchResult']['@count']
    item_dict = content_dict['findCompletedItemsResponse']['searchResult']['item']
    print('count:', count)
    content_df = extract_values(item_dict)
    x_values = content_df['endPrice'].tolist()
    y_values_b = content_df['endTime'].tolist()
    y_values = convert_datetime(y_values_b)
    context = {
        'response': content_df.to_html(),
        'content_df': content_df,
        'x_v': x_values,
        'y_v': y_values
    }
    return render(request, 'display_graphs/graphs.html', context)
'''
def get_time_graph(request):
    fig, ax = plt.subplots()
    ax.set_title('Scatter plot of prices over time')
    ax.set_xlabel('dates')
    ax.set_ylabel('sell prices')
    ax.scatter(content_df.endDate.values, content_df.endPrice.values, s=10, label='sell prices over time')
    canvas = FigureCanvasAgg(fig)
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    plt.close(fig)
    response = HttpResponse(buf.getvalue(), content_type='image/png')
    canvas.print_png(response)
    context = {'first_graph':response}
    return render(request, 'display_graphs/graphs.html', context)
'''
def to_dict(input_ordered_dict):
    return loads(dumps(input_ordered_dict))

def extract_values(temp_dict):
    df = pd.DataFrame(columns=['itemId','title','endPrice','location','endTime'])
    a = []
    b = []
    c = []
    d = []
    f = []
    #print('\ntype of data:\n', type(temp_dict))
    length = len(temp_dict)
    print('\nlength:\n', length)
    for index in range(length):
        for key, value in temp_dict[index].items():
            print('temp_dict[index][key]:', key)
            if key == 'itemId':
                a.append(value)
            if key == 'title':
                b.append(value)
            if key == 'sellingStatus':
                c.append(temp_dict[index]['sellingStatus']['currentPrice']['#text'])
            if key == 'location':
                d.append(value)
            if key == 'listingInfo':
                f.append(temp_dict[index]['listingInfo']['endTime'])
    df = pd.DataFrame({'itemId':pd.Series(a),'title':pd.Series(b),'endPrice':pd.Series(c),'location':pd.Series(d),'endTime':pd.Series(f)})  
    #print('\ndf:\n', df)
    #print('\narray a:\n', a)
    #print('\narray b:\n', b)
    #print('\narray c:\n', c)
    #print('\narray d:\n', d)
    #print('\narray f:\n', f)
    df['endTime'] = pd.to_datetime(df['endTime']) # datetime ISO 8601 format ---> YYYY-MM-DD HH:MM:SS +HH:MM (NOTE: '+HH:MM' is UTC offset)
    df['endTimeOfDay'],df['endDate'] = df['endTime'].apply(lambda x:x.time()),df['endTime'].apply(lambda x:x.date())
    return df

def convert_datetime(arr):
    arr2 = []
    for i in arr:
        dateobj = str(i)
        dateobj = dateobj[:19]
        arr2.append(int(datetime.datetime.strptime(dateobj, "%Y-%m-%d %H:%M:%S").timestamp())*1000)
        print('convert_datetime ',arr2[-1])
        #print('dateobj:', dateobj)
    return arr2

display_graphs/graphs.html

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'display_graphs/style.css' %}">
    <title>Display graphs page</title>
    <style>
        ul {
          list-style-type: none;
          margin: 0;
          padding: 0;
          overflow: hidden;
          background-color: #333;
        }

        li {
          float: left;
        }

        li a {
          display: block;
          color: white;
          text-align: center;
          padding: 14px 16px;
          text-decoration: none;
        }

        li a:hover:not(.active) {
          background-color: #111;
        }

        .active {
          background-color: #4CAF50;
        }
  </style>
  </head>
  <body>
      <div>
        <ul>
          <li><a class="active" href="/">Home</a></li>
          <li><a href="/blog">Blog</a></li>
          <li><a href="/contact">Contact Us</a></li>
          <li><a href="/about">About Us</a></li>
        </ul>
      </div>
      <div class="parallax5" align="center">
          <h1 style="background-color:white;align:center;color:red;padding:20px;width:50%;">Graph Page</h1>
              <p style="background-color:white;align:center;color:black;padding:50px;width:70%;">
                  Graphs are displayed below:</p><br>
                  <div id="container"></div>
                    <script src="https://code.highcharts.com/highcharts.src.js"></script>
                      <script>
                        Highcharts.chart('container', {
                            chart: {
                                type: 'scatter',
                                zoomtype:'xy'
                            },
                            title: {
                                text: 'Sell prices over time'
                            },
                            xAxis: {
                                title: {
                                    text: 'price'
                                },
                                type: 'datetime',
                            },
                            yAxis: {
                                title: {
                                    text: 'end date'
                                }
                            },
                            series: [{
                                data: x_v
                            }, {
                                data: y_v
                            }]
                        });
                      </script>

                  {% autoescape off %}
                      {{ response }}                    
                  {% endautoescape %}

              <br>

      </div>
  </body>
</html>

查詢的樣本日期是:2019-09-30 23:11:17+00:00 對應的值變成了自紀元以來的毫秒數:1569899477000

根據我看過的所有文檔和網站,圖表應該顯示,但不是。 我不明白為什么。 如果您需要更多信息並希望查看到目前為止的代碼,那么這里是github 存儲庫的鏈接github 存儲庫鏈接我想指出我已經檢查了 x 的所有值、數據類型和值計數- 軸和 y 軸。 兩個 python 列表的計數都是 100。 x 軸的數據類型(所有浮點值)都是浮點數。 y 軸的數據類型都是以紀元毫秒為單位的整數(從格式為 YYYY-MM-DD HH:MM:SS 的時間戳轉換而來)。 兩個列表的數據都沒有錯誤。 我已經在命令行上手動檢查過。 我只是不知道為什么圖表不會顯示。 理論上應該。 我在這個問題上花了大約 8 個多小時。 這真的很令人沮喪。

所以我想出了如何在我的 django 模板上顯示圖表。 錯誤一:我不得不將我的價格(浮點數)從字符串更改為浮點數數據類型。 錯誤二:我將浮動(賣出價格)傳遞到 x 軸,而不是 y 軸。 我把斧頭弄混了。 錯誤三:我不得不將兩個列表壓縮為 (x,y) 對。 具有兩個元素的數組列表。 這使一個系列。 數組中的第一個元素是 x 值,第二個值是 y 值。

修復:我必須將數據傳遞到上下文中的 django 模板到圖表腳本部分中的變量。 代碼段如下:

<div id="container"></div>
                    <script src="https://code.highcharts.com/highcharts.js"></script>
                    <script src="https://code.highcharts.com/modules/series-label.js"></script>
                    <script src="https://code.highcharts.com/modules/exporting.js"></script>
                    <div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
                      <script>
                        chart1 = {{ chart1|safe }};
                        Highcharts.chart('container', {
                            chart: {
                                type: 'spline'
                            },
                            title: {
                                text: 'Sell prices over time'
                            },
                            xAxis: {
                                type: 'datetime',
                                dateTimeLabelFormats: {
                                    month: '%e. %b',
                                    year: '%b'
                                },
                                title: {
                                    text: 'Date'
                                }
                            },
                            yAxis: {
                                title: {
                                    text: 'price'
                                },
                                min: 0
                            },
                            series: [{
                                data: chart1
                            }]
                        });
                      </script>

重要的代碼段是這樣的:

chart1 = {{ chart1|safe }};

這是我相應的views.py中的代碼:

from django.shortcuts import render
from ebaysdk.finding import Connection as finding
import xmltodict
from json import loads, dumps
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import io
from matplotlib.backends.backend_agg import FigureCanvasAgg
from django.http import HttpResponse

content_df = pd.DataFrame()

def display_the_graphs(request):
    keywords = request.POST.get('search')
    api = finding(appid='JohnHein-homepage-PRD-392e94856-07aba7fe', config_file=None, siteid='EBAY-US')
    api_request = {'keywords':keywords, 'itemFilter':[{'name':'SoldItemsOnly', 'value':True},]}
    response = api.execute('findCompletedItems', api_request)
    content = response.content
    xml_dict = xmltodict.parse(content)
    content_dict = to_dict(xml_dict)
    count = content_dict['findCompletedItemsResponse']['searchResult']['@count']
    item_dict = content_dict['findCompletedItemsResponse']['searchResult']['item']
    print('count:', count)
    content_df = extract_values(item_dict)
    y_values = content_df['endPrice'].tolist()
    y_values = [float(i) for i in y_values]
    x_values_b = content_df['endTime'].tolist()
    x_values = convert_datetime(x_values_b)
    print('\nx_values: ', x_values,'\n')
    print('\ny_values: ', y_values,'\n')
    print('\nx_values count:', len(x_values),'\n')
    print('\ny_values count:', len(y_values),'\n')
    print('\nx_values type:', type(x_values[-1]),'\n')
    print('\ny_values type:', type(y_values[-1]),'\n')
    chart1_data = list(zip(x_values, y_values))
    print('chart1 data:', chart1_data)
    context = {
        'response': content_df.to_html(),
        'content_df': content_df,
        'chart1': chart1_data
    }
    return render(request, 'display_graphs/graphs.html', context)
'''
def get_time_graph(request):
    fig, ax = plt.subplots()
    ax.set_title('Scatter plot of prices over time')
    ax.set_xlabel('dates')
    ax.set_ylabel('sell prices')
    ax.scatter(content_df.endDate.values, content_df.endPrice.values, s=10, label='sell prices over time')
    canvas = FigureCanvasAgg(fig)
    buf = io.BytesIO()
    plt.savefig(buf, format='png')
    plt.close(fig)
    response = HttpResponse(buf.getvalue(), content_type='image/png')
    canvas.print_png(response)
    context = {'first_graph':response}
    return render(request, 'display_graphs/graphs.html', context)
'''
def to_dict(input_ordered_dict):
    return loads(dumps(input_ordered_dict))

def extract_values(temp_dict):
    df = pd.DataFrame(columns=['itemId','title','endPrice','location','endTime'])
    a = []
    b = []
    c = []
    d = []
    f = []
    #print('\ntype of data:\n', type(temp_dict))
    length = len(temp_dict)
    print('\nlength:\n', length)
    for index in range(length):
        for key, value in temp_dict[index].items():
            print('temp_dict[index][key]:', key)
            if key == 'itemId':
                a.append(value)
            if key == 'title':
                b.append(value)
            if key == 'sellingStatus':
                c.append(temp_dict[index]['sellingStatus']['currentPrice']['#text'])
            if key == 'location':
                d.append(value)
            if key == 'listingInfo':
                f.append(temp_dict[index]['listingInfo']['endTime'])
    df = pd.DataFrame({'itemId':pd.Series(a),'title':pd.Series(b),'endPrice':pd.Series(c),'location':pd.Series(d),'endTime':pd.Series(f)})  
    #print('\ndf:\n', df)
    #print('\narray a:\n', a)
    #print('\narray b:\n', b)
    #print('\narray c:\n', c)
    #print('\narray d:\n', d)
    #print('\narray f:\n', f)
    df['endTime'] = pd.to_datetime(df['endTime']) # datetime ISO 8601 format ---> YYYY-MM-DD HH:MM:SS +HH:MM (NOTE: '+HH:MM' is UTC offset)
    df['endTimeOfDay'],df['endDate'] = df['endTime'].apply(lambda x:x.time()),df['endTime'].apply(lambda x:x.date())
    return df

def convert_datetime(arr):
    arr2 = []
    for i in arr:
        dateobj = str(i)
        dateobj = dateobj[:19]
        arr2.append(int(datetime.datetime.strptime(dateobj, "%Y-%m-%d %H:%M:%S").timestamp())*1000)
        #print('convert_datetime ',arr2[-1])
        #print('dateobj:', dateobj)
    return arr2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM