Friday, June 6, 2014

Displaying images

As I mentioned in a previous post, <img src = ""> does not work in Django. I mean, it does work, and that's how we are going to display images, but it doesn't work if you give local machine addresses like /home/foo/bar or C:/images/foo/bar. This is actually a good thing. Django has a very sophisticated method of handling images and other files, often called as static files.
If you open your settings.py file, you'll see two URLs: STATIC_URL and MEDIA_URL. These can be used to render static files and media in general.
Now there are two ways of doing this:
  • Using the in-built {{ STATIC_URL }} or {{ MEDIA_URL }} variables. But as I have not posted about Django's templating language, we'll put this one on the back burner. But rest assured, once you understand the templating language, how to use these will be self-evident.
  • Using full URLs, including the values specified in {{ STATIC_URL }} and {{ MEDIA_URL }}
We'll be using the second method. The only disadvantage of this method is that if the directory containing static files changes then you have to make sure that change reflects in all templates. In the first case, this would happen automatically.

Let's assume you're running your website on localhost, i.e. http://127.0.0.1/ and you want to render an image on the URL http://127.0.0.1/home. Let's also assume that the .html file behind this webpage is called home.html (wow, that's a lot of assuming).

Anyway, change into your project directory, and create a folder called static. Store all your images here. Let's assume (not again!) that you have an image called garden.jpg in the static folder, which you want to display on the homepage.

So instead of giving local machine paths, you give the path in the form of a URL.

<img src  = "http://127.0.0.1/static/garden.jpg">

Now, to validate this, open your settings.py file, and make the following changes.

STATIC_ROOT = "/foo/bar/mysite/static"
STATIC_URL = "/static/"

This will tell Django that when http://127.0.0.1/static/ (or STATIC_URL) is accessed, the path in STATIC_ROOT is to be checked.

That's all for now! Two things before we part:
  • I'm still working on the templating tutorial, to make it concise as it is a very vast topic. Once I come up with it, we'll investigate the {{ STATIC_URL }} and {{ MEDIA_URL }} business.
  • What we did here with static can also be done with media. They are two objects of the same file displaying facility, giving us more customizability. To use media, just replace static with media in all of the code above.
Cheers!

No comments:

Post a Comment