-2

I have created an user input form after selection of which a graph is displayed, the heading of the graph result I have named as 'Results' but the results heading is displayed even before user selection

Here is the pic enter image description here

I haven't selected anything yet. Once I select from the drop down it displays something like this enter image description here

A full graph is displayed

I don't want the heading Results to be displayed before the drop down selection what should I do?

Here is my html code snippet

{% if result != None %}
      <div>
        <h2 style="color: #105583;"><a class="article-title">Results</a></h2>
        <img src="data:image/png;base64,{{ result }}"\>
      </div>
{% elif result == None %}  
      <div>
        <h2 style="color: #105583;">
<a class="article-title">Your results will be displayed here</a></h2>
      </div>
{% endif %}    

This what I have written in my html file, if y'all need any other piece of code to be displayed, I shall edit the post accordingly

Here is the route

@app.route('/DailyStats', methods=['GET','POST'])
def DailyStats():
   if request.method=='POST':
        timelineSelect = request.form['selectedTimeline']
        dateSelect = request.form['selectedDate']

        if(timelineSelect=='Daily'):
            import datetime
            idx=get_date.index(dateSelect)
            df['d'] = pd.to_datetime(df['date_time'], format='(%Y,%m,%d,%H,%M,%S)')
            day1 = df['d'].dt.date[idx]
            df1 = df[df['d'].dt.date.eq(day1)]
            df1 = df1.melt(['date_time','d']) 
            df1 = df1[df1['value'].eq('Y')]
            d = df1.groupby('variable')['date_time'].apply(list).to_dict()
            d = {k: [x.time() for x in v] for k, v in d.items()}
            xpoints=[]
            ypoints=[]
            for x in d:
                for y in d[x]:
                    xpoints.append(y)
                    ypoints.append(x)
            x_dt = [datetime.datetime.combine(datetime.date.today(), t) for t in xpoints]
            fig, ax = plt.subplots()
            plt.plot([],[],)
            ax.scatter(x_dt,ypoints, marker='_')
            ax.set_title('Usage % of Hardware on '+ dateSelect)
            plt.yticks(size=5, fontsize=10)
            plt.xticks(rotation=85,fontsize=10)
            plt.xlabel('Time')
            plt.ylabel('Apps')
            plt.tick_params(axis="y",length=5, color="red")
            plt.grid(color='gray', linestyle='-', linewidth=0.5)
            plt.tight_layout()
            myFmt = mdates.DateFormatter("%H")
            ax.xaxis.set_major_formatter(myFmt)
            print(myFmt)
            print(ax.xaxis.set_major_formatter(myFmt))

            ## Rotate date labels automatically
            fig.autofmt_xdate()
            from io import BytesIO
            fig = BytesIO()
            plt.savefig(fig, format='png')
            fig.seek(0) 
            import base64
            figdata_png = base64.b64encode(fig.getvalue())
    return render_template('datasetDisplay.html', result=figdata_png.decode('utf8'))
Glen Veigas
  • 85
  • 1
  • 12
  • What does `print(result)' in python show? It seems like it's not None, so your Jinja condition is trying to show it. – janpeterka Nov 15 '20 at 10:30
  • Hi, I followed the steps from this answer to display the graph https://stackoverflow.com/questions/31492525/converting-matplotlib-png-to-base64-for-viewing-in-html-template, now when I ```print(type(result))``` it displays `````` – Glen Veigas Nov 15 '20 at 11:12
  • See, so it seems like your template never gets None. Show more of your route/controller logic which makes this page :) – janpeterka Nov 15 '20 at 11:31
  • I have added the route in the question – Glen Veigas Nov 15 '20 at 12:59

1 Answers1

2

Ok, so I guess when you first load your page, it skips all the logic (as it's "POST" only) and gets directly to render_template. How it gets figdata_png for putting in variable is mystery to me, but it seems to place something there. So, your solution could be to have

if request.method == "POST":
  (your code)
  result = figdata_png.decode("utf-8")
elif request.method == "GET":
  result = None

return render_template(..., result=result)
  
janpeterka
  • 568
  • 4
  • 17