How to include image files in Django templates?

I am new to Django and I am trying to learn it through a simple project that I am developing under the name of "dubliners" and an application called "book". The directory structure looks like this:

dubliners/book/ [includes models.py, views.py, etc.] dubliners/templates/book/ 

I have a jpg file that should appear in the title of each web page. Where should I store the file? Which way should I use for a tag to display it using a template? I tried different places and paths, but so far nothing is working.

...

Thanks for the answer below. However, I tried both relative and absolute paths to the image, and I still get the broken image icon displayed on the web page. For example, if I have an image in my home directory and use this tag in my template:

 <img src="/home/tony/london.jpg" /> 

Image is not displayed. However, if I save the web page as a static HTML file, the images are displayed, so the path is correct. Maybe the default web server that comes with Django will only display images if they are on a specific path?

+53
python django django-templates
May 23 '09 at 1:45
source share
10 answers

In the production process, you simply create HTML code from your template, indicating where the media files are stored on the host. Thus, your template will have, for example,

 <img src="../media/foo.png"> 

And then you just make sure that the directory exists with the appropriate files.

during development is another problem. The django docs explain this briefly and clearly enough that it’s more efficient to link and enter them here, but basically you define a view for the site with a hard code for the path to the disk location.

Right here .

+27
May 23 '09 at 2:04
source share

Try it,

settings.py

 # typically, os.path.join(os.path.dirname(__file__), 'media') MEDIA_ROOT = '<your_path>/media' MEDIA_URL = '/media/' 

urls.py

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

.html

 <img src="{{ MEDIA_URL }}<sub-dir-under-media-if-any>/<image-name.ext>" /> 

Caveat

Caution! using Context() , you get an empty value for {{MEDIA_URL}} . Instead, you should use RequestContext() .

Hope this helps.

+62
Aug 05 '09 at 20:25
source share

I understand that your question was about files stored in MEDIA_ROOT, but sometimes you can store the contents in static when you no longer plan to create this type of content.
Maybe this is a rare case, but in any case - if you have a huge number of "pictures of the day" for your site - and all these files are located on your hard drive?

In this case, I see no contradiction for storing such content in STATIC.
And everything becomes very simple:

static

Link to static files stored in STATIC_ROOT Django comes with a static template tag. You can use this no matter if you use RequestContext or not.

{% load static %} <img src="{% static "images/hi.jpg" %}" alt="Hi!" />

copied from django 1.4 Official Documentation / Built-in Tags and Template Filters

+13
Sep 10
source share

I spent two hard days working on this, so I just decided to share my decision. As of 26/11/10, the current branch is 1.2.X, so you will need to have the following .py options at your disposal:

 MEDIA_ROOT = "<path_to_files>" (ie /home/project/django/app/templates/static) MEDIA_URL = "http://localhost:8000/static/" 

* (remember that MEDIA_ROOT are files, and MEDIA_URL is a constant that you use in your templates.) *

Then in your url.py specify the following:

 import settings # stuff (r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), 

Then in your html you can use:

 <img src="{{ MEDIA_URL }}foo.jpg"> 

How django works (as far as I can understand:

  • In the html file, it replaces MEDIA_URL with the path MEDIA_URL found in settings.py
  • It searches url.py to find matches for MEDIA_URL, and then if it finds a match (for example, r '^ static / (? P.) $' * refers to http: // localhost: 8000 / static /) it looks for the file in MEDIA_ROOT and then loads it.
+10
Nov 26 '10 at 11:42 on
source share

/ media catalog at the root of the project

Settings.py

 BASE_DIR = os.path.dirname(os.path.dirname(__file__)) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') 

urls.py

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

template

 <img src="{{MEDIA_URL}}/image.png" > 
+6
May 23 '15 at 9:58
source share

If your file is a model field inside the model, you can also use ".url" in the template tag to get the image.

For example.

If this is your model:

 class Foo(models.Model): foo = models.TextField() bar = models.FileField(upload_to="foo-pictures", blank = True) 

Pass the model in context in your views.

 return render (request, "whatever.html", {'foo':Foo.objects.get(pk = 1)}) 

In the template, you can:

 <img src = "{{foo.bar.url}}"> 
+5
Sep 08 '14 at 12:58 on
source share

Your

 <img src="/home/tony/london.jpg" /> 

will work for an HTML file read from disk, as it will read the URL file:///home/... For a file served from a web server, the URL will look something like this: http://www.yourdomain.com/home/tony/london.jpg , which may be an invalid URL, and not what you actually you mean.

About how to service and where to place your static files, check out this. Basically, if you use the django development server, you want to show it where your media files are, and then run urls.py these files (for example, using some URL /static/ prefix).

Asks you to add something like this to urls.py :

 (r'^site_media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/path/to/media'}), 

In a production environment, you want to skip this and make your HTTP server (apache, lighttpd, etc.) serve static files.

+4
May 23 '09 at
source share

In developing
In the application folder, create the folder name "static" and save the image in this folder.
Image Usage:

 <html> <head> {% load staticfiles %} <!-- Prepare django to load static files --> </head> <body> <img src={% static "image.jpg" %}> </body> </html> 

In production:
Everything is the same as in development, just add a couple more parameters for Django:

  • add settings.py
    STATIC_ROOT = os.path.join(BASE_DIR, "static/") (this will prepare a folder in which static files from all applications will be stored)

  • make sure your application is in INSTALLED_APPS = ['myapp',]

  • in the terminall run python manage.py collectstatic command (this will make a copy of the static files from all applications included in INSTALLED_APPS to the global static folder - the STATIC_ROOT folder)

    Thats all Django needs, after that you need to do some web server settings to make the conditions for using a static folder. For example. in apache2 in the httpd.conf configuration file (for Windows) or with the /000-default.conf sites. (under the virtual host part of the site for Linux) add:

    Alias ​​\ static "path_to_your_project \ static"

    Require all provided

    And that's all

+4
Mar 14 '17 at 13:11
source share

Another way to do this:

 MEDIA_ROOT = '/home/USER/Projects/REPO/src/PROJECT/APP/static/media/' MEDIA_URL = '/static/media/' 

This will require you to move the media folder to a subdirectory of the static folder.

Then in the template you can use:

 <img class="scale-with-grid" src="{{object.photo.url}}"/> 
+2
Jun 22 '12 at 17:44
source share

I tried a different method, it did not work. But it worked. Hope this works for you too. The file / file directory should be in the following places:

PROJEC / your_app / project templates / your_app / static

settings.py

 import os PROJECT_DIR = os.path.realpath(os.path.dirname(_____file_____)) STATIC_ROOT = '/your_path/static/' 

Example:

 STATIC_ROOT = '/home/project_name/your_app/static/' STATIC_URL = '/static/' STATICFILES_DIRS =( PROJECT_DIR+'/static', ##//don.t forget comma ) TEMPLATE_DIRS = ( PROJECT_DIR+'/templates/', ) 

projected / application / templates / filename.html

inside the body

 {% load staticfiles %} //for image img src="{% static "fb.png" %}" alt="image here" //note that fb.png is at /home/project/app/static/fb.png 

If fb.png was inside /home/project/app/static/image/fb.png, then

 img src="{% static "images/fb.png" %}" alt="image here" 
+1
Jun 11 '13 at 4:59
source share



All Articles