How to display image in django template

11,104 views
Skip to first unread message

d

unread,
Oct 25, 2010, 6:34:38 AM10/25/10
to Django users
Hi all
I have been searching for solutions whole day.
How would I display image file in django template. I have already set
MEDIA_ROOT and MEDIA_URL.

Can some one show a step by step instruction as it will help a lot of
other people.

Thanks!

Venkatraman S

unread,
Oct 25, 2010, 6:41:25 AM10/25/10
to django...@googlegroups.com

On Mon, Oct 25, 2010 at 4:04 PM, d <ryan.z....@gmail.com> wrote:
I have been searching for solutions whole day.
How would I display image file in django template. I have already set
MEDIA_ROOT and MEDIA_URL.


You mean image as in static image or from Image model?
If static image, then this is the process:
- lets say image is in ProjectNameFolder/static/images/img1.jpeg
- Have this in your settings.py
import os.path
BASE_PATH = os.path.dirname(__file__)
SITE_ROOT = BASE_PATH
STATIC_DOC_ROOT = BASE_PATH+'/static'
-  In your urls.py:

if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_DOC_ROOT}),
    )

- in your template <img src="/static/images/img1.jpeg"/>

This should work. Note that this serves the static content from the django dev server and should be used purely in your dev env.

-V-
http://twitter.com/venkasub

Kenneth Gonsalves

unread,
Oct 25, 2010, 6:42:06 AM10/25/10
to django...@googlegroups.com
On Mon, 2010-10-25 at 03:34 -0700, d wrote:
> I have been searching for solutions whole day.
> How would I display image file in django template. I have already set
> MEDIA_ROOT and MEDIA_URL.

assume a model:

Mymodel(models.Model):
photo = models.ImageField("somename",upload_to="images/")

get an instance:

myob = Mymodel.objects.get(pk=1)

in your template:

<img src="{% myob.photo.url %}">
--
regards
Kenneth Gonsalves
Senior Associate
NRC-FOSS at AU-KBC

girish shabadimath

unread,
Oct 27, 2010, 5:20:41 AM10/27/10
to django...@googlegroups.com
Another way for static images:
Its good to have all html related stuffs (html files, images, ..etc) in one directory (ex: html directory)

In settings.py there is a field called TEMPLATE_DIR, add the absolute-path to the html directory to this filed
ex: TEMPLATE_DIR = 'path-to-html-directory',

in template, access the image as <img src="path to html dir">    



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.




--
Girish M S
Reply all
Reply to author
Forward
0 new messages