18

I want to print an image by using a img src tag in a Django template file "base.html":

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
    <title>Foto</title>
</head>
<body>
    <h1>My helpful timestamp site</h1>
    <img src="google.png" / >
    <hr>
    <p>Made by ... </p>
</body>
</html>

In views.py I define:

def hello(request):
    return render_to_response('base.html')

But the image does not show up in the browser. If I open it as a simple html file, it shows up in the browser.

user1680859
  • 1,160
  • 2
  • 24
  • 40

3 Answers3

26

In recent versions of django

<img src="{% static 'path/to/image.ext' %}"/>

chandan
  • 964
  • 1
  • 19
  • 26
17

That happens because Django does not know the path to this image.
Make a folder named static/, and then a folder named images/ in your project root(where your settings.py file resides).

my_project/
    my_project/ 
        settings.py
        static/
           images/
             google.png

And then change it to:

<img src="{{STATIC_URL}}images/google.png" / >

More here.

thikonom
  • 4,219
  • 3
  • 26
  • 30
  • Since I have only one image, I didn't want to use static files. I saw from the https://docs.djangoproject.com/en/1.0/ref/templates/builtins/ the example: – user1680859 Sep 18 '12 at 17:20
  • This is just an example. The common way to go is the one that i described in my answer. – thikonom Sep 18 '12 at 17:33
10

You have got to add load static tag in the beginning of your Django template, best luck with below code.

{% load static %} 
<img src="{% static 'path/to/image.ext' %}"/>
WEshruth
  • 769
  • 3
  • 16
  • 32