4

I am new to django. I tried to load an image through HTML(graph.html). views.py includes

def avg_duration_vs_time_of_day(request):
    figName="figGraph.png"
    path="Telecom/Images/"+figName
    day = [1, 2, 3, 4]
    query = "select time_of_day,avg(duration) from fact_table group by time_of_day"
    avg_call_day = connect(query)
    import matplotlib.pyplot as plt
    plt.figure(figsize = (4,4))
    plt.xlabel("Time of Day",fontdict={'fontsize':8})
    plt.ylabel("Average Call Duration in seconds",fontdict={'fontsize':8}) 
    plt.title("Average Call Versus Time of Day",fontdict = {'fontsize':8})
    plt.plot(day,avg_call_day,color='green', linestyle='solid',linewidth=1, marker='o',markerfacecolor='blue', markersize=0)
    plt.bar(day,avg_call_day,width=0.2,align='center')
    plt.savefig(path)
    image_data = open(path, "rb").read()
    context = { 'image_data': image_data }    
    return render_to_response('welcome/graph.html', context)

graph.html includes

<div>
<img src="{% 'views.avg_duration_vs_time_of_day.image_data' %} " />
</div>

But image cannot load in the browser and the error is

TemplateSyntaxError at /graph/
Invalid block tag: ''views.avg_duration_vs_time_of_day.image_data''

What is the solution ?

1 Answer 1

2

You should put image path in a template context, instead of image itself:

context = { 'image_path': path }    
return render_to_response('welcome/graph.html', context)

And, your template syntax is incorrect:

<div>
<img src="{{ image_path }}"/>
</div>

Hope your settings are configured properly. FYI, see:

Hope that helps.

Sign up to request clarification or add additional context in comments.

6 Comments

I have changed my settings.py as MEDIA_ROOT = os.path.join(PROJECT_DIR, 'Images/media') MEDIA_URL = 'localhost:8000/media/admin' but it is not working properly I have saved that image in Images directory inside my project folder
Then, save your image inside MEDIA_ROOT.
I don't understand what you mean ?
I changed MEDIA_ROOT = os.path.join(PROJECT_DIR, 'Images') but still not working
Try as MEDIA_ROOT = '/path_on_you_server/images/' and MEDIA_URL = '/images/'. After you must save your images into the folder '/path_on_you_server/images/'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.